Javascript

解决vue-router报NavigationDuplicated: Avoided redundant navigation to current location 的问题

本文主要是介绍解决vue-router报NavigationDuplicated: Avoided redundant navigation to current location 的问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

场景:在 App.vue文件中通过watch全局监听本地中是否有 token,若没有,则跳转到登录页;若有,则return。

 1 app.vue代码
 2 
 3 watch: {
 4     $route() {
 5       if (!localStorage.getItem("token")) {
 6         this.$router.push("/login");
 7       } else {
 8         return;
 9       }
10     }
11   }

虽然跳转到登录页了,但是控制台报错了,如下:

 

 查阅相关资料,总结原因:watch监控执行了两次,导致了重复触发了同一个路由。

且在跳转前后两行分别打印了99 和 '-----',结果发现确实打印了两次:

 

 对于报错,已找到了解决办法:

在route.js文件中写入以下代码即可:

1 const originalPush = Router.prototype.push
2 
3 Router.prototype.push = function push(location) {
4   return originalPush.call(this, location).catch(err => err)
5 }

结果发现控制台中的报错消失了。

这篇关于解决vue-router报NavigationDuplicated: Avoided redundant navigation to current location 的问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!