vue-router重复push出现NavigationDuplicated问题解决

Web前端 潘老师 4年前 (2020-09-14) 2710 ℃ (0) 扫码查看

我们在学习vue-router的编程式导航时,我们发现如果多次重复点击某个按钮触发页面跳转,会出现如下“NavigationDuplicated”错误,这里我先贴上我的部分代码:

// template中菜单按钮
<button @click="toBlog">博客</button>

// 对应的click事件的跳转方法
toBlog(){
    this.$router.push("/blog");
}

// 路由配置
{
    name:"Blog",
    path:"/blog",
    component:()=>import('@/components/Blog.vue')
}

连续多次点击博客按钮,会出现如下错误:

NavigationDuplicated: Avoided redundant navigation to current location: “/blog”.

vue-router重复push出现NavigationDuplicated问题解决
虽然对代码运行没有任何影响,但是看上去还是很不爽!

1、问题出现原因:

重复路由跳转,我们当前路由是博客页面/blog,但是再点击博客按钮进行this.$router.push操作,要跳转的页面还是/blog博客页面。

2、解决办法有两种:

1)升级vue-router版本为3.0即可解决,打开项目终端运行如下命令:

npm i vue-router@3.0 -S

2)修改VueRouter原型对象上的push方法,在router文件夹下的index.js中的Vue.use(VueRouter)代码下方加入如下代码:

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/java/web/1222.html
喜欢 (8)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】