用户按下浏览器后,Vuejs 未触发挂载

Lee*_*521 7 vue.js vue-router vuejs2

在我的 vuejs 应用程序上有一个仪表板,用户可以单击一个按钮将他发送到 /room ( router.push("/room");)。

当用户到达页面时,会触发“mounted”函数并发出一个简单的console.log。这样可行。

mounted() {
    console.log("room mounted");
}
Run Code Online (Sandbox Code Playgroud)

如果用户按下浏览器的“后退”按钮并返回到仪表板,他可以再次单击该按钮加入房间,但这次不会触发“已安装”功能。

有办法让它发挥作用吗?

谢谢。

Lan*_*ose 2

根据Vue Router GitHub 存储库上的此问题,这是 Vue Router 中的预期行为:

这是预期的行为,Vue 会尽可能重用组件。

您可以使用 beforeRouteUpdatehook 对使用相同组件的路由切换做出反应。

Navigating "back" to an already-mounted component won't trigger a subsequent mounting of the component. To see which lifecycle hooks are triggered on Route Update, you can look at this blog post (scroll down to the Lifecycle Hooks diagram).

The situation you're running into is the "Client Update" column, where mounted is not called, but update is. In general, I tend to utilize parallel code in both beforeRouteEnter and beforeRouteUpdate. Sadly, it's a bit repetitive.