在定义路由的时候可以设置一个meta字段,里面是我们想要校验的值,比如页面上的某两个模块需要登录后才能查看,我们就在这两个路由上设置meta:
{
path: '/learn',
name: 'learn',
meta: { //路由元信息
login: true
},
component: ()=>{
return import('./views/Learn'); //懒加载
}
},
如何访问这个meta字段呢?
通过路由导航守卫的to来查看:
//路由全局守卫
router.beforeEach((to, from, next)=> {
console.log(to);
console.log(to.matched); //路由里面包含的路径信息
const needLogin = to.matched.some(item => item.meta && item.meta.login);
if(needLogin){
const isLogin = document.cookie.includes('login=true');
if(isLogin){
next();
}else{
const toLoginFlag = window.confirm('该页面需要登录后访问,要去登陆吗?');
if(toLoginFlag){
next('/login');
}
}
}else{
next();
}
});
打印这个to,可以看到里面有meta这个字段:
但如果我们设置的路由有redirect重定向,这个meta字段就是空的。
这种情况就需要查看to.matched里面的值,matched里存放的是路由包含的路径的所有信息,打印这个matched:
这样就能找到meta字段了。