vue-router报错Invalid navigation guard
场景
vue版本3、vue-router版本4。
在main.js文件内使用beforeEach,运行项目,随后就报错了
router.beforeEach((to, from, next) => {
console.log('*************************', to, from);
if (to.name === "destructuring") {
// 返回 false 以取消导航
return false
} else {
next()
}
})
问题分析
在百度上搜索Invalid navigation guard的报错原因和解决办法。
说法有很多种,最多的是删除 node_modules,重新npm i 就好了。
试了,根本不起作用。
于是乎,我继续阅读文档,希望能从其中找到解决办法。可惜,beforeEach部分仔细看了好几遍都没有找到解决的办法。
突破点
仔细查看报错,发现上面还有一条警告
翻译中文的意思就是如果你return了一个value,而不是调用next(),那么你应该将移除next函数。
优化后
1、第一种解决方案
// 去掉next
router.beforeEach((to, from) => {
console.log('*************************', to, from);
if (to.name === "destructuring") {
// 返回 false 以取消导航
return false
}
})
再重新编译代码,完美,没有报错了,问题解决。
2、第二种解决方案
// 不采用return false
router.beforeEach((to, from,next) => {
console.log('*************************', to, from);
if (to.name === "destructuring") {
// next(false) 以取消导航
next(false)
} else{
next()
}
})
总结
return一个值和next()两种方式只能选择一种。在一起使用会报错