1. 程式人生 > >vue-router路由元資訊meta

vue-router路由元資訊meta

1. 前言:

在全域性守衛beforeEach((to,from,next) => {...})中判斷當前路由是否允許登入、是否需要身份認證、許可權認證等,雖然可以採用路由匹配的方式 if(to.path === '/url'),很顯然當需要驗證的路由較多時,會增加太多的if判斷,這不利於程式碼維護,此時可在定義路由的時候可以配置 meta 欄位,通過設定一些屬性值,可以便於我們對當前的路由做一些處理,也可以使用next()重定向到其他路由。 2. 使用,在定義路由時定義一個需要驗證的meta資訊 meta: {requiresAuth: true}

路由記錄可以是巢狀的,因此,當一個路由匹配成功後,他可能匹配多個路由記錄,例如,根據下面的路由配置,/foo/bar

 這個 URL 將會匹配父路由記錄以及子路由記錄,

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

一個路由匹配到的所有路由記錄會暴露為 $route

 物件 的 $route.matched 陣列。因此,我們需要遍歷 $route.matched 來檢查路由記錄中的 meta 欄位,

然後在全域性導航守衛中檢查元欄位是否需要驗證

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 確保一定要呼叫 next()
  }
})