如果在 vue-router 中找不到匹配的路由,则强制重新加载

Force Reload if no matching route is found in vue-router

我正在努力解决 vue-router 的问题。 我需要检查一个简单的条件,即

If no matching route is found. Do window.location.reload()

我正在使用 vue-router:2.7.0,vue 是 2.4.2

我浏览了大量的博客 post,但没有找到直接的答案。

我会把代码扔进去然后解释。

const router = new VueRouter({
  mode: 'history',
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    window.location.reload();
  }
  next();
});

router.beforeEach在路由加载前调用,有3个参数。 to, from and next。接下来是一个回调函数。
这里的关键是to参数中匹配的属性。它包含一组匹配的路由。如果没有找到匹配的路由,to.matched数组的长度变为0,也就是我用来做判断的属性。

vue-router中应该有另外一种属性。但那是一场我改天再打的仗。