【问题标题】:Vue router reloading the current routeVue路由器重新加载当前路由
【发布时间】:2019-08-26 21:56:51
【问题描述】:

在不重新加载整个页面的情况下,我需要在 vue 应用程序中再次重新加载当前路由(仅重新加载组件)。

我在 vue 路由器中有一条路径,如下所示,

{
  path: "/dashboard",
  name: "dashboard",
  component: loadView("Dashboard"),

},

当用户点击 Dashboard 导航项时,用户将被重定向到带有 vue router 编程导航的 Dashboard 页面

this.$router.push({ name: "dashboard" });

但是当用户已经在仪表板路线中并且用户再次单击仪表板导航项时,没有任何反应。我认为这是 vue 路由器的默认行为。但是我需要强制重新加载仪表板组件(不要刷新整个页面)。

我不能使用 beforeRouteUpdate,因为路由器没有更新。我也尝试过像 beforeEach 这样的全局前警卫。但它也不起作用。

如何在不重新加载整个页面的情况下强制重新加载仪表板组件?

【问题讨论】:

标签: vuejs2 vue-router


【解决方案1】:

这可以通过两种方式完成。

1) 尝试做 vm.$forceUpdate();按照建议here

2) 你可以采取将key分配给children的策略,但是每当你想重新渲染一个组件时,你只需更新key即可。

<template>
  <component-to-re-render :key="componentKey" />
</template>

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

每次调用 forceRerender 时,prop componentKey 都会改变。发生这种情况时,Vue 会知道它必须销毁组件并创建一个新组件。

你得到的是一个子组件,它会重新初始化自己并“重置”它的状态。

【讨论】:

    【解决方案2】:

    此处未提及,但由于提供的解决方案需要大量额外工作才能使应用正确呈现,而 imo 是一个脆弱的解决方案。我们刚刚实施了另一个运行良好的解决方案。

    虽然这完全是一个黑客攻击。

        if (this.$route.name === redirect.name) {
          // this is a filthy hack - the vue router will not reload the current page and then have vue update the view.
          // This hack routes to a generic page, then after this has happened the real redirect can happen
          // It happens on most devices too fast to be noticed by the human eye, and in addition does not do a window
          // redirect which breaks the mobile apps.
          await this.$router.push({
            name: RouteNames.ROUTE_REDIRECT_PLACEHOLDER
          });
        }
    
    ... now continue to do your normal redirect.
    

    基本上,重定向到一个占位符,等待响应,然后立即继续到您真正想要移动的另一个页面

    【讨论】:

    • 这不会污染历史吗?
    • 是的,但我知道没有其他方法无需深度集成解决方案
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2018-04-20
    • 2016-10-20
    • 2014-02-24
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多