Vue Router 推送错误:避免了到当前位置的冗余导航

dun*_*ack 4 javascript typescript vue.js vue-router

有没有办法避免错误:避免冗余导航到当前位置。我需要进行分页,方法如下:

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

我不断在控制台中收到错误:

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

我尝试用路由器进行捕获,但这不起作用。有人可以帮助我阐明我在这里做错了什么吗?:/

Wen*_* Du 6

如果忽略它是安全的,并且您正在使用 vue-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)
  }
})
Run Code Online (Sandbox Code Playgroud)

或者全局处理:

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)
Run Code Online (Sandbox Code Playgroud)

更多详情,请参阅导航失败