簡體   English   中英

如何在Vue中使用防護來忽略路由規則?

[英]How to use a guard in vue to ignore the route rule?

如何使用防護來移動到下一條路由規則,而不是重定向到特定路由?

例如,我有一些路線:

 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(例如login)的示例,這沒有幫助。

當我給url:'/ some'然后vue檢查是否:

  1. 是/嗎? 否=>下一條路線。
  2. / about是? 否=>下一條路線。
  3. 是/:product? 否=>下一條路線。
  4. 顯示NotFoundException組件。

您可以按路線名稱引用下一條路線。

首先,命名您的例外路線

 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 }
 ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM