Make writing a habit together! This is my first day to participate in the “Gold Digging Day New Plan · April More text challenge”, click to see the details of the activity.

Question:

In this project, you need to check whether the user logs in. If the user does not log in or the token expires, you need to switch to the login page for login authentication. So you need to do an interception and report an error on the login page.

The error is shown in the following figure:

Cause: This error is an internal error of vue-router, which does not carry out catch processing, resulting in a programmatic navigation jump problem, which will report an error when jumping to the same address (push and replace will both cause this situation).

Solution:

Solution 1: Install vue-Router 3.0 or earlier. Uninstall vue-Router 3.0 or later and then install the earlier version.

npm install vue-router@2.8. 0 -S
Copy the code

Scheme 2: Add catch for the same address to catch exceptions.

this.$router.push({path:'/register'}).catch(err= > { console.log(err) })
Copy the code

Option 3: Add the following code to the router

// Resolve the problem of programmatic routes jumping to the same address
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err= > err);
};

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err= > err);
};
Copy the code

Corresponding document and location:

expand

Router. push, router.replace, router.go in Vue Router

The equivalent of the router. Push (location)windowPushState To navigate to a different URL, use the router.push method. This method adds a new record to the history stack, so when the user clicks the browser back button, it returns to the previous URL. The router. The replace equivalent (location)window.history.replaceState is similar to router.push, except that it does not add a new record to history, but replaces the current one. The router. The go (n) is equal towindow.history.go jumps forward or backward to n pages. N can be a positive or negative integer. Can be achieved bywindow.history.length gets how many pages there are in the history stack.Copy the code

The navigation methods of Vue Router (push, replace, and Go) are consistent in history, Hash, and abstract routing modes.

Portal: A new window opens in the Vue Router