具体场景:在Vue中使用编程式导航多次点击出错,Vue路由跳转报错Avoided redundant navigation to current location: “/xxxxxx“.
原因和解决方法如下:
编程式导航多次点击路由时报错的原因是因为
vue-router在3.1.0版本之后,push和replace方法会返回一个promise对象,如果不捕获异常,控制台会报错
解决方法:在router/index.js中加入以下代码(可能每个人的路由配置文件不同,下面放一下我的)
代码注释里面有非常详细的原因和解释说明
// 下面是解决编程式导航多次点击路由时报错的方法'
//编程式导航多次点击路由时报错的原因是因为
//vue-router在3.1.0版本之后,push和replace方法会返回一个promise对象,如果不捕获异常,控制台会报错
//解决方法:在router/index.js中加入以下代码
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function push(location) {
// 解释一下下面代码
// 1.首先调用原来的push方法,将location传进去
// 2.然后调用catch方法,捕获异常
// 3.最后返回一个promise对象
return originalPush.call(this, location).catch(err => err);
};
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
};
我的index.js文件如下
import VueRouter from "vue-router";
import Home from "../components/Home.vue";
import Course from "../components/Course.vue";
import Front from "../components/Front.vue";
import Back from "../components/Back.vue";
const routes = new VueRouter({
routes: [
{
path: "/home1",
// 下面这行代码的意思是:当访问 /home 路径时,加载 Home 组件
// component: () => import("../components/Home.vue"),
component:Home,
},
{
path: "/course",
component:Course,
children:[
{
path:"front",
component:Front,
},
{
// 如果使用params传参,参数为对象的形式,那么必须要在路由这里单独加name属性,可以不加path后面的text参数
name:'houduan',
path:"back/:text",
component:Back,
},
]
},
],
});
// 下面是解决编程式导航多次点击路由时报错的方法'
//编程式导航多次点击路由时报错的原因是因为
//vue-router在3.1.0版本之后,push和replace方法会返回一个promise对象,如果不捕获异常,控制台会报错
//解决方法:在router/index.js中加入以下代码
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function push(location) {
// 解释一下下面代码
// 1.首先调用原来的push方法,将location传进去
// 2.然后调用catch方法,捕获异常
// 3.最后返回一个promise对象
return originalPush.call(this, location).catch(err => err);
};
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
};
export default routes;
我的调用代码如下
methods: {
toFront() {
// this.$router.push({path:'/course/front',query:{text:this.text}})
// this.$router.push({ name: "houduan", params: { text: this.text } });
this.$router.replace({ name: "houduan", params: { text: this.text } });
},
},