温馨提示×

解决vue路由跳转报错,Navigation cancelled ……to with a...

vue
小云
692
2023-09-28 09:08:32
栏目: 编程语言

当使用Vue Router进行路由跳转时,如果出现"Navigation cancelled from …… to with a new navigation"错误,通常是由于在路由跳转过程中重复点击了相同的路由链接或者使用了router.push()方法进行了多次异步路由跳转。

解决方法:

  1. 检查代码中是否存在多次点击相同路由链接的情况,可以通过给路由链接添加@click.prevent事件来阻止多次点击,或者使用<router-link-exact-active>标签来确保只有在路由完全匹配时才会添加活动类。

  2. 如果是通过router.push()方法进行异步路由跳转,可以使用router.replace()方法来替代,确保每次只进行一次路由跳转。

  3. 如果以上方法都无效,可以尝试在路由跳转前添加this.$router.currentRoute.meta.keepAlive = false来取消路由的缓存,然后再进行跳转。

示例代码:

<template>
<div>
<router-link to="/home" @click.prevent>Home</router-link>
<router-link to="/about" @click.prevent>About</router-link>
<router-link-exact-active to="/home">Home</router-link-exact-active>
<router-link-exact-active to="/about">About</router-link-exact-active>
</div>
</template>
<script>
export default {
methods: {
goToHome() {
this.$router.replace('/home');
},
goToAbout() {
this.$router.replace('/about');
}
}
}
</script>

希望以上方法能够解决你的问题。

0