【问题标题】:Vue Router push Error: Avoided redundant navigation to current locationVue路由器推送错误:避免了到当前位置的冗余导航
【发布时间】:2021-04-28 22:01:43
【问题描述】:

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

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".

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

【问题讨论】:

  • 实际上,您正试图导航到您当前所在的同一页面,这就是您遇到导航重复错误的原因。例如:您在 xyz 页面上,并且您再次尝试导航到同一个 xyz 页面。
  • 你也可以试试这个this.$router.push({ name: 'PageName', query }).catch(err => {})
  • 嗨,我尝试了您的解决方案,它似乎在第一页到第二页上都可以工作,如果我导航到第三页等等,它将无法工作,而且 cmiw 也只是抑制了错误消息。
  • 您可以尝试添加一个条件,如果当前路径/查询与路由路径不同,则仅更改路径,否则不更改。 if (this.$route.path !== path) this.$router.push(path)

标签: javascript typescript vue.js vue-router


【解决方案1】:

如果可以安全忽略,并且您使用的是 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)
  }
})

更多详情请参考Navigation Failures

【讨论】:

    【解决方案2】:

    您可以全局处理此问题。 打开路由器的索引文件 (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) => {
      });
    };
    

    试试这个例子 - here

    干杯!

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2011-06-17
      • 1970-01-01
      • 2011-06-16
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多