Vue Router 路由元信息

路由元信息

配置meta字段

{
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home'),
    meta: {requiresAuth: true}
}

访问meta字段

路由记录

称呼routes配置中的每个路由对象为路由记录(RouteRecord)。路由记录可嵌套(children),所以当一个路由匹配成功,它可能匹配多个路由记录(父路由记录及子路由记录)。

$route对象以及在导航守卫中的路由对象(to、from)中的matched数组是一个路由匹配到的所有路由记录

访问meta字段的某个key值

举个栗子🌰:

想要实现在每次请求前,都判断是否需要登录(这个信息从meta中requiresAuth字段拿)。

导航守卫:

router.beforeEach((to, from, next) => {
    if (to.matched.some((record) => {
        console.log(record)
        console.log(record.meta)
        return record.meta.requiresAuth
    })) {
        console.log(111)
        if (!auth.loggedIn()) {
            next({
                path: '/login',
                query: {redirect: to.fullPath}
            })
        } else {
            next()
        }
    } else {
        next()
    }
})

路由对象:

{
    path: '/:id',
    name: 'Home',
    component: () => import('@/views/Home'),
    props: route => ({
        query: route.query.q
    }),
    beforeEnter: (to, from, next) => {
        console.log('路由守卫:beforeEnter')
        console.warn(to + ',' + from);
        next();
    },
    children: [
        {
            path: 'about',
            component: () => import('@/views/About'),
            meta: {requiresAuth: true}
        }
    ]
}

前文说了,$route和to、from都是路由对象,只要是路由对象都有matched数组,里面有meta属性,即路由元信息。

some()是js中的一个数组方法,用来测试数组中的元素是否通过了指定函数的测试。

some(callback回调函数),回调函数返回一个布尔值,some()为数组每个元素都执行一次回调函数,直到返回一个‘真’值停止。

如果遍历到最后,仍旧没有找到‘真’值,则some()返回false,否则在找到‘真’值的那一刻返回true。

上面🌰中的导航守卫逻辑:

if(该路由请求是否需要登录验证(通过找meta信息中的requiresAuth值为依据)){

    //需要验证

        if(!登录验证){

            //登录验证失败

            跳转到登录页面登录

        } else{

           //登录验证成功

           放行

        }

} else{

    //不需要验证

   放行

}

上面🌰中的路由信息:

父路由记录没有meta,而子路由记录有meta,且值为true。

将record和record.meta的结果打印出来:

从结果上看,matched数组中有父路由记录(/:id)及子路由记录(/:id/about),some()将其全部遍历出来了。

record的打印结果展开:

其实就是路由配置中的路由对象。

为什么要some()遍历?直接to.matched.meta不行吗?

这不显而易见吗,matched可是个数组,包含了所有路由记录,并不能找到指定路由记录,只能是遍历。

想找到指定路由记录的路由元信息,可以判断一下:

router.beforeEach((to, from, next) => {
    if (to.matched.some((record) => {
            if (record.name === 'Home') {
                console.log(record.meta.requiresAuth)
            }
            return record.meta.requiresAuth
        }
    )) {
        console.log('xxx')
    }
    next()
})
posted @ 2021-10-18 00:06  慕斯星球  阅读(229)  评论(0)    收藏  举报