码迷,mamicode.com
首页 > 其他好文 > 详细

编程式路由跳转到当前路由, 控制台抛出NavigationDuplicated的错误

时间:2020-07-14 13:35:46      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:push   UNC   ace   location   call   bsp   回调函数   color   实例化   


router.push 的语法规则如下:

router.push(location(导航路径), onComplete(成功的回调)?, onAbort?(失败的回调))
router.push(location).then(onComplete).catch(onAbort)
router.replace 的语法规则如下:

router.replace(location, onComplete?, onAbort?)
router.replace(location).then(onComplete).catch(onAbort)
解决方案一:

methods: {
//执行 toSearch() 方法后,跳转路由
toSearch(){
this.$router.push(‘/search‘) //————重复点击会报错:NavigationDuplicated
//解决方法如下:
this.$router.push(‘/search‘ , ()=>{})
//或者
this.$router.push(‘/search‘ , undefined , ()=>{})
//或者
this.$router.push(‘/search‘) .catch(()=>{})
}
}

解决方案二:
每次调用push 或者 replace 方法都要写回调函数,很麻烦,因此可以在Vue原型上重构这两个方法,重构时给两个回调函数其中一个指定默认值或者指定catch

 1 import Vue from ‘vue‘
 2 import VueRouter from ‘vue-router‘
 3 Vue.use(VueRouter)
 4 
 5 
 6 //终极解决多次触发push或者repalce,报错的问题
 7 //NavigationDuplicated
 8 
 9 const originPush = VueRouter.prototype.push
10 const originReplace = VueRouter.prototype.replace
11 
12 //location为传过来的对象
13 VueRouter.prototype.push = function(location,onResolved,onRejected){
14   if(onResolved === undefined && onRejected === undefined){
15     // originPush.call目的是让VueRouter实例化对象去调用‘
16     //如果不加,那就是window在调用
17     return originPush.call(this,location).catch(() => {})
18   }else{
19     return originPush.call(this,location,onResolved,onRejected)
20   }
21 }
22 
23 VueRouter.prototype.replace = function(location,onResolved,onRejected){
24   if(onResolved === undefined && onRejected === undefined){
25     // originPush.call目的是让VueRouter实例化对象去调用‘
26     //如果不加,那就是window在调用
27     return originReplace.call(this,location).catch(() => {})
28   }else{
29     return originReplace.call(this,location,onResolved,onRejected)
30   }
31 }
32 
33 
34 import routes from ‘@/router/routes‘
35 
36 export default new VueRouter({
37   routes
38 })

 


原文链接:https://blog.csdn.net/qq_38763173/article/details/105349152

编程式路由跳转到当前路由, 控制台抛出NavigationDuplicated的错误

标签:push   UNC   ace   location   call   bsp   回调函数   color   实例化   

原文地址:https://www.cnblogs.com/fsg6/p/13298470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!