Vue路由器推送错误:避免冗余导航到当前位置



是否有办法避免错误:避免冗余导航到当前位置。我需要做一个分页,这是方法:

handlePageChange(page: number): void {
const query = {
...this.$route.query,
page: page.toString(),
};
this.$router.push({ name: 'PageName', query });
}

和我一直得到错误在控制台:

Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/page-path?page=2".

我试着用路由器做一个捕获,但那不起作用。有人能告诉我我做错了什么吗?:/

如果忽略它是安全的,并且你正在使用vui -router^3.4.0,你可以这样做:

import VueRouter from 'vue-router'
const { isNavigationFailure, NavigationFailureType } = VueRouter
...
this.$router.push(fullPath).catch(error => {
if (!isNavigationFailure(error, NavigationFailureType.duplicated)) {
throw Error(error)
}
})

或者全局处理:

import Vue from 'vue'
import VueRouter from 'vue-router'
const { push } = VueRouter.prototype
const { isNavigationFailure, NavigationFailureType } = VueRouter
VueRouter.prototype.push = function (location) {
return push.call(this, location).catch(error => {
if (!isNavigationFailure(error, NavigationFailureType.duplicated)) {
throw Error(error)
}
})
}
Vue.use(VueRouter)

详细信息请参见导航故障。

你可以全局处理这个问题。打开路由器的索引文件(index.js),并在其中使用以下代码-

import VueRouter from "vue-router";
Vue.use(VueRouter);
// Handle navigation duplication for router push (Globally)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch((error) => {
});
};

试试这个例子-这里

干杯!

这有点过时了,但是为了更清晰的全局处理,合并了两个现有的答案:

import VueRouter from "vue-router";
Vue.use(VueRouter);
const { isNavigationFailure, NavigationFailureType } = VueRouter;
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
original_push.call(this, location).catch(error => {
if(!isNavigationFailure(error, NavigationFailureType.duplicated)) {
throw Error(error)
}
})
};

最新更新