路由元信息

85 阅读1分钟

路由元信息

访问路由会带过去的默认信息

存在meta 字段中

const routes = [
  {
    path: '/posts',
    component: ...,
    children: [
      {
        path: ...,
        component: ...,
        // 只有经过身份验证的用户才能创建帖子
        meta: { requiresAuth: true,a:1 }
      },
      {
        path: ...,
        component: ...,
        // 任何人都可以阅读文章
        meta: { requiresAuth: false,a:1 }
      }
    ]
  }
]

组件使用

<div>{{ $route.meta.a }}</div>

路由使用

router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !auth.isLoggedIn()) {
    // 此路由需要授权,请检查是否已登录
    // 如果没有,则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置,以便以后再来
      query: { redirect: to.fullPath },
    }
  }
})