如何知道 back/forward 是否被按下而不是手动路由器推入 vue/vue-router?

How to know if back/forward was pressed instead of a manual router push in vue/vue-router?

在 vue/vue-router 中,我在 $route 上有一个观察者,它以两种方式触发。

  1. 我在浏览器上点击后退或前进。
  2. 用户与表单交互,表单使用的变量上有观察者,然后这些观察者函数使用 $router.push.
  3. 更新 url

那么在 $route 的 watcher 函数中,我如何知道发生了上述两种情况中的哪一种?

问题是,如果出现了第一种情况,我想再次手动更新表单。如果情况2发生,表格已经更新了,所以我不想再次手动更新表格。

So then in the watcher function for $route, how do I know which of the above 2 scenarios occurred?

你不能。观察者将在观察值以任何方式发生变化时执行,您不会知道是什么导致回调中的值发生变化。

如果您想知道路由何时因用户单击 back/forward 浏览器按钮而发生变化,您需要为 popstate 事件添加一个事件侦听器。

The problem is, if scenario 1 occurred, I want to manually update the form again. If scenario 2 happened, the form will have have already been updated, so I don't want to manually update the form again.

对 URL params/query 中的数据进行任何 更改时,我没有看到更新表单的问题;您可以检查 URL 数据是否与表单数据相同并跳过更新。

这似乎可以解决问题

window.onpopstate = function(event) {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

它在我后退或前进时运行,而不是在我手动更新时运行 URL。