【问题标题】:How to use a guard in vue to ignore the route rule?vue中如何使用守卫忽略路由规则?
【发布时间】:2019-12-14 07:48:00
【问题描述】:

如何使用守卫移动到下一条路由规则而不是重定向到特定路由?

例如,我有一些路线:

 routes: [
   { path: '/', component: Main },
   { path: '/about', component: About },
   { path: '/:product', component: Product },
   { path: '*', component: NotFoundException }
 ]

在 Product 组件中我有 beforeRouteEnter 这样的功能:

 beforeRouteEnter(to, from, next) {
   const question = checkIfExist(to.params.product);
   if (question) { next(); return;}

   next();
 }

如果产品不存在,那么它应该被重定向到 NotFoundException 组件。在 stackoverflow 示例中,我只看到重定向到特定 url(如登录)的示例,这没有帮助。

当我给出 url: '/some' 然后 vue 检查是否:

  1. 是/?没有 => 下一条路线。
  2. 是 /about 吗?没有 => 下一条路线。
  3. 是/:产品?没有 => 下一条路线。
  4. 显示 NotFoundException 组件。

【问题讨论】:

  • 你真正想要达到什么目的? .请明确目标
  • 如果产品不存在,那么它应该是'/',这是你的主组件

标签: vue.js vue-router


【解决方案1】:

您可以通过路线名称引用下一条路线。

首先,命名您的异常路径

 routes: [
   { path: '/', component: Main },
   { path: '/about', component: About },
   { path: '/:product', component: Product },
   { path: '*', name: 'notFound', component: NotFoundException }
 ]

然后,创建一个变量来存储您的 beforeEnter 逻辑

const productExists = (to, from, next) => {
   const question = checkIfExist(to.params.product);
   if (question) { next(); return;}
   next({
      name: "notFound"
   });
}

将路由守卫添加到您要保护的路由中

 routes: [
   { path: '/', component: Main },
   { path: '/about', component: About },
   { path: '/:product', component: Product, beforeEnter: productExists },
   { path: '*', name: 'notFound', component: NotFoundException }
 ]

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 2021-10-04
    • 2018-12-04
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 2019-02-04
    相关资源
    最近更新 更多