处理 this.$router.replace(href);在 vue 2

问题描述 投票:0回答:1

我是 vue 新手,正在处理我之前创建的 vue 代码。因此,有很多遗留代码太复杂,现在无法更改。

当用户想要导航到 DynamicReport 时,vue 代码可以处于两种状态之一,它们可能位于该组件上,也可能不位于该组件上。我试图解决的问题是,当用户使用 DynamicReport 并且代码执行推送时,它会收到 NavigationDuplicated 错误。我已更改代码以进行替换,但这不会触发已安装的处理程序。因此,我试图弄清楚当用户想要导航到新报告时如何重新初始化组件。

这是在App.vue中:

      viewReportNotification: function(report) {
        const { href } = this.$router.resolve({
          name: 'DynamicReportWithId',
          params: { reportResultsId: report.reportResultsId } // Route parameters
        });

        console.log(`this.$route.path: ${this.$route.path}`)
        console.log(`href: ${href}`)
        if (this.$route.path !== href) {
          if (this.$route.path.startsWith('/DynamicReport/')) {
            console.log(`trying to replace: ${href}`)
            this.$router.replace(href);
          } else {
            console.log(`trying to PUSH: ${href}`)
            this.$router.push(href);
          }
        }
      },

我尝试将其添加到组件中,但是

beforeRouteUpdate
没有被调用:

  beforeRouteUpdate: function(to, from, next) {
    console.log(`beforeRouteUpdate( ${to}, ${from}, ...)`);
    if (to.type === 'replace') {
      console.log(`replacing ${from} with ${to}`);
      this.loadReportIfQueryParamsExist();
    }
    next();
  },
  mounted: function() {
    this.loadReportIfQueryParamsExist();
    this.handlePanelOpen();
  },

再说一遍,我是 vue 代码的新手,我确信有很多更好的方法来完成整个事情,但是......我只是想修复一个错误,而不是现在重新设计整个事情。

vuejs2 vue-component vue-router
1个回答
0
投票

由于您尝试导航到同一页面,因此正在发生此问题。您可以做的是,因为您知道需要推送/替换到相同的 URL,所以您可以尝试重新加载组件,以便这将重新运行已安装的生命周期(另外,由于您提到了遗留问题,我假设您正在使用vue 2)

您可以尝试使用->

vm.$forceUpdate();

这里 vm 是 Vue 实例

另一种首选方法是组件化报告视图并使用密钥,只需更改它即可重新渲染组件,这样子组件(此处为报告组件)将重新渲染。

<template>
  <report-component :key="componentKey" />
</template>

<script>
export default {
  data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;  
    }
  }
}
</script>

现在,只要查询发生变化,您就可以调用 forceRerender() 方法,从而重新运行已安装的方法

© www.soinside.com 2019 - 2024. All rights reserved.