如果最后一项不是 Vue 路由,如何为 router.back() 提供替代方案?

How to provide an alternative for router.back() if the last item is not a Vue route?

我在 vue-router 中使用 router.back()。它有效,但我可以预见的问题是用户可能会通过直接访问访问没有历史记录的页面。那个或用户来自另一个域。

这两种情况都是不需要的。如果之前的路线不是正确的 Vue 路线,我想提供一个替代方案。

所以在那种情况下,我想推送类似 this.$router.push({ name: 'deal-list' });

的内容,而不是 router.back()

我知道可以使用 route.beforeEach 检查路由,我已经在我的 router.js 文件中使用它来维护我的查询参数,如下所示:

router.beforeEach((to, from, next) => {
    if (!hasQueryParams(to) && hasQueryParams(from)) {
        next({ name: to.name, query: from.query });
    }

    next();
});

我如何在组件 中检查 虽然之前的路线是什么并相应地调整我的 link?

使用vue router,可以直接在组件上设置一个beforeRouteEnter hook,获取对之前路由的引用。

this变量没有引用这个钩子中的Vue实例。但是,您可以通过传递给 next 函数的回调中的第一个参数引用 Vue 实例(本例中为 vm):

data() {
  return {
    previousRoute: null,
  }
},
beforeRouteEnter(to, from, next) {
  next(vm => vm.previousRoute = from);
}

Here's the documentation on navigational guards.