Vue路由器重载当前路由

use*_*438 7 vue-router vuejs2

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

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

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

},
Run Code Online (Sandbox Code Playgroud)

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

this.$router.push({ name: "dashboard" });
Run Code Online (Sandbox Code Playgroud)

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

由于路由器未更新,我无法使用 beforeRouteUpdate。我也尝试过像 beforeEach 这样的全局前守卫。但它也不起作用。

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

Rid*_*dhi 4

可以通过两种方式完成。

\n\n

1)尝试执行 vm.$forceUpdate(); 正如这里所建议的。

\n\n

2)您可以采取为子级分配键的策略,但是每当您想要重新渲染组件时,只需更新键即可。

\n\n
<template>\n  <component-to-re-render :key="componentKey" />\n</template>\n\n<script>\nexport default {\n  data() {\n    return {\n      componentKey: 0,\n    };\n  },\n  methods: {\n    forceRerender() {\n      this.componentKey += 1;  \n    }\n  }\n}\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

您得到的是一个子组件,它将重新初始化自身并 \xe2\x80\x9creset\xe2\x80\x9d 其状态。

\n