乐闻世界logo
搜索文章和话题

Vue - router - How to get previous page url?

1个答案

1

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.

javascript
let 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.

  1. 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(); });
  1. 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.

  1. 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;
  1. Update the state in the global before-route guard:
javascript
router.beforeEach((to, from, next) => { store.commit('setPreviousUrl', from.fullPath); next(); });
  1. Retrieve the state in a component:
javascript
computed: { 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.

2024年6月29日 12:07 回复

你的答案