【Vue2】NavigationDuplicated: Avoided redundant navigation to current location:xxxxx

2023-07-30,,

翻译过来就是,导航重复:避免了到当前位置的冗余导航。
简单来说就是重复跳转了相同路径

原因

触发这种情况是因为vue-router中引入了primise,当传递了多次重复的参数就会抛出异常,而这种问题是只有编程式导航才会出现的,因为这个问题在声明式导航中已经在内部解决了这个问题。

解决方案

路由的pushreplace都是VueRouter原型对象上的一个方法,所以每次路由跳转的时候都是通过这两个方法来实现,而这两个方法提供了三个参数,VueRouter.prototype.push(location,resolve,reject)分别是

包含了路由以及携带参数的location
成功失败回调 resolve reject

解决方案大致上就是两种,

    一种是在 push | replace 的时候传递成功与失败的回调来处理异常。
    这种方式有一个缺点就是每次调用都需要传递成功与失败的回调有些麻烦。

    this.$router.push(
    { //第一个参数包含了路由跳转的一些信息 也就是router-link中的to,push方法中的location
    name:"home",
    params:{...},
    query:{...}
    },
    ($router)=>{}, //第二个参数是成功后的回调,可以通过第一个参数接收到$router对象
    (err)=>{console.log(err)} // 第三个参数是失败后的回调,导航重复会在此处抛出异常
    )

    第二种是重写VueRouter原型对象中的push | replace方法,通过在上面新增一个判断来处理程序抛出的异常信息。
    这种方式修改过后再跳转路由就不需要再像第一种方式那样传递回调了

    //保存一份 push | replace 方法,方便接下来重写方法
    let originPush = VueRouter.prototype.push
    let originReplace = VueRouter.prototype.replace
    // 重写push方法
    VueRouter.prototype.push = function (location,resolve,reject){
    if (resolve && reject){ //如果传入了resolve和reject两个回调,则正常执行原来的push方法
    originPush.call(this,location,resolve,reject)
    }else{ // 否则就执行指定的方法
    originPush.call(this,location,($router)=>{},(err)=>{
    console.log(err)
    }} VueRouter.prototype.replace = function(...){...}

【Vue2】NavigationDuplicated: Avoided redundant navigation to current location:xxxxx的相关教程结束。

《【Vue2】NavigationDuplicated: Avoided redundant navigation to current location:xxxxx.doc》

下载本文的Word格式文档,以方便收藏与打印。