vue重复路由报错解决
Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation…
分为三种解决方式
1.捕获异常
在项目的src\router\index.js
全局设置捕获路由引起的异常
//屏蔽重复路由警告
const VueRouterPush = router.push
router.push = function push(to) {
undefined
return VueRouterPush.call(this, to).catch(err => err)
}
export default router
也可以在具体方法中实际this.$router.push()
时单独设置捕获异常
this.$router.push('路径').catch(err => err)
2.判断路由再跳转
if(this.$route.path !== '路径'){
this.$router.push('路径');
}
3.中转至空白页replace()
先创建一个空白页BlankPage.vue
并配置相应的路由
在项目的src\main.js
中定义全局跳转方法
//全局刷新页面方法
Vue.prototype.$routeTo= function (targetRoutePath) {
this.$router.push({
path: '/BlankPage',
query: {
routerPath: targetRoutePath,
}
})
}
在BlankPage.vue
中设置路由替换
created() {
let routerPath = this.$route.query.routerPath
this.$router.replace(routerPath)
}
将方法中原先的路由跳转改为全局跳转方法即可
this.$router.push('路径');
修改为this.$routeTo('路径')
拓展
使用空白页中转可以实现简单的页面刷新效果(路由指向自身页面),这种刷新页面不会全部重新加载,体验较好
如果想要带参数空白页中转路由,可以把上面的方法稍加修改
步骤
先创建一个空白页BlankPage.vue
并配置相应的路由
//全局刷新页面方法
Vue.prototype.$routeTo= function (targetRoutePath,res) {
this.$router.push({
path: '/BlankPage',
query: {
routerPath: targetRoutePath,
res:res
}
})
}
res用于存储跳转时传参
在BlankPage.vue
中设置路由替换
created() {
let routerPath = this.$route.query.routerPath
let res=this.$route.query.res
this.$router.replace({
path:routerPath,
query:{
res:res
}
})
}
将方法中原先的路由跳转改为全局跳转方法即可
将
this.$router.push({
path:'路径',
query:{
参数1:值1,
参数2:值2,
参数3:值3,
……
}
});
修改为
this.$routeTo('路径',
{
参数1:值1,
参数2:值2,
参数3:值3,
……
}
});
在目标页接收参数
let 参数1 = this.$route.query.res.参数1
let 参数2 = this.$route.query.res.参数2
let 参数3 = this.$route.query.res.参数3
…
修改后的跳转方法也可以不传参跳转,即this.$routeTo('路径')