In Vue, when using Vue Router for route management, the Vue Router instance does not directly provide a built-in method to retrieve the previous page URL. However, you can achieve this requirement through several methods.
Method 1: Using the browser's document.referrer
This is the simplest method, as you can directly retrieve the URL of the previously visited page using JavaScript's document.referrer. This property returns the URL of the page accessed before the current one; if no previous page exists, it returns an empty string.
javascriptlet previousUrl = document.referrer; console.log(previousUrl); // Print the previous URL
Method 2: Listening for route changes and manually saving
Vue Router provides navigation guards, where you can listen for route changes and save the current route so that you can access the previous route when navigation occurs.
- Set up a global before-route guard in your main Vue instance:
javascript// main.js or router/index.js router.beforeEach((to, from, next) => { // Save the page you came from localStorage.setItem('previousUrl', from.fullPath); next(); });
- Read the previous URL where needed:
javascript// In a component or anywhere else let previousUrl = localStorage.getItem('previousUrl'); console.log(previousUrl);
Method 3: Using Vuex for state management
If your application structure is complex and you need to share route state across multiple components, consider using Vuex to manage these states.
- Define a module in Vuex to store route state:
javascript// store.js const store = new Vuex.Store({ state: { previousUrl: '' }, mutations: { setPreviousUrl(state, url) { state.previousUrl = url; } } }); export default store;
- Update the state in the global before-route guard:
javascriptrouter.beforeEach((to, from, next) => { store.commit('setPreviousUrl', from.fullPath); next(); });
- Retrieve the state in a component:
javascriptcomputed: { previousUrl() { return this.$store.state.previousUrl; } }
These are several common methods to retrieve the previous page URL in Vue. Based on your specific needs and the complexity of your application, you can choose the appropriate method to implement.