[Solve vue-router error: Navigation canceled from “/…” to “/…” with a new navigation]

Problem:
In the project, it is necessary to judge whether the user is logged in. If the user is not logged in or the token expires, it is necessary to jump to the login page for login verification. So you need to do an interception, and an error is reported when you jump to the login page.

The error is shown in the figure below:

insert image description here
Reason:
This error is an internal error of vue-router, without catch processing, resulting in a programmatic navigation jump problem, and an error will be reported when jumping to the same address (both push and replace will cause this to happen).

 

Solution:
Solution 1:
Install vue-router version below 3.0, uninstall version above 3.0 and then install the old version.

npm install [email protected] -S



Solution 2:
Add a catch to the same address as the routing jump to catch the exception.

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



Solution 3:
Add the following piece of code to the index.js file in the router
 

// 解决编程式路由往同一地址跳转时会报错的情况
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);
};

The diagram is as follows

insert image description here

 

expand

The difference between router.push, router.replace and router.go in Vue Router

router.push(location) 相当于 window.history.pushState
想要导航到不同的 URL,则使用 router.push 方法。
这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

router.replace(location) 相当于 window.history.replaceState
跟 router.push 很像,区别:它不会向 history 添加新记录,而是替换掉当前的 history 记录,点击返回会跳转到上上个页面。

router.go(n) 相当于 window.history.go
向前或者向后跳转n个页面,n可为正整数或负整数。可以通过 window.history.length 得到历史记录栈中一共有多少页。



 

Guess you like

Origin blog.csdn.net/m0_65450343/article/details/126324123