其他分享
首页 > 其他分享> > 解决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,return,watch,redundant,current,报错,location,跳转,push
来源: https://www.cnblogs.com/heisetianshi/p/15966505.html