How to store previous page url as string in vue.js?

by hal.littel , in category: Third Party Scripts , 10 days ago

How to store previous page url as string in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 9 days ago

@hal.littel 

You can store the previous page URL as a string in Vue.js by using Vue Router's navigation guards. Here's one way to do it:

  1. In your Vue component, import the Vue Router:
1
import { createRouter, createWebHistory } from 'vue-router';


  1. Create a new router instance and configure it with the createWebHistory function:
1
2
3
4
5
6
const router = createRouter({
  history: createWebHistory(),
  routes: [
    // Define your routes here
  ]
});


  1. Add a beforeRouteLeave navigation guard to store the previous page URL when the user navigates away from the current page:
1
2
3
4
5
router.beforeRouteLeave((to, from, next) => {
  // Store the previous page URL in a data property
  this.$data.previousPageUrl = from.fullPath;
  next();
});


  1. Finally, make sure to include the router instance in your Vue app:
1
2
const app = createApp(App);
app.use(router);


Now, you can access the previous page URL as a string in your Vue component by referencing the previousPageUrl data property.