12.路由元信息meta

158 阅读1分钟

1. 路由配置routers中配置 meta 字段

定义路由的时候可以配置 meta 字段:

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

2. 访问meta 字段

首先,我们称呼 routes 配置中的每个路由对象为 路由记录。路由记录可以是嵌套的路由对象,因此,当一个路由匹配成功后,它可能匹配多个路由记录

例如,根据上面的路由配置,/foo/bar 这个 URL 将会匹配父路由记录以及子路由记录。

image.png

一个路由匹配到的所有路由记录会暴露为 $route 对象 (还有在导航守卫中的路由对象) 的 $route.matched 数组。因此,我们需要遍历 $route.matched 来检查路由记录中的 meta 字段。

image.png

下面例子展示在全局导航守卫router.beforeEach中检查元字段meta

const Login = {
        template: `<div class="Login">
                      <h2>Login {{ $route.query.redirect}}</h2>
                    </div>`
      };
router.beforeEach((to, from, next) => {
        // record 路由记录
        if (to.matched.some(record => record.meta.requiresAuth)) {
          // 至少有一条路由记录中的meta有requiresAuth值
          next({
            path: "/login",
            query: { redirect: to.fullPath }
          });
        } else {
          next(); // 确保一定要调用 next()
        }
      });