为何会有这个东西呢?
咱们知道咱们浏览一些网站的时候有须要验证登陆的也有不须要验证登陆的,若是全部页面都在作成验证登陆的话对于用户的体验也是极差的,因此这个时候路由元信息就起到了很大的做用。cookie
主人公:meta字段session
介绍:
咱们称每一个路由对象为路由记录,路由记录能够嵌套。因此到咱们匹配到一个路有的时候他有可能有多条路由记录。路由记录会暴露在对应路由对象上,咱们能够经过$route.matched获取到当前路由全部的路由记录,$route.matched[n].meta能够获取其中一个路由记录的meta字段函数
栗子:网站
let routes = [{ path: '/foo', name: 'foo', component: foo, children: [{ path: 'bar', component: bar, meta: { needLogin: true//须要判断登陆 } }] }, { path: '/login', name: 'login', component: login }];
假设localhost:8080为项目地址
当访问localhost:8080/#/foo/bar
的时候咱们须要判断登陆怎么办呢
上代码(用到了导航守卫的全局守卫中的beforeEach):localstorage
let router = new VueRouter({ routes }); router.beforeEach((to, from, next) => { //判断路由记录是否须要验证登陆 if(to.matched.some(current => current.meta.needLogin)){ //只要记录上须要登陆 咱们就得验证 /* * 本身封装方法判断登陆 sessionstorage localstorage cookie啥的自行决定 */ let isLogin = getLoginStatus();//本身定义的判断登陆的方法 if(!isLogin) { next({ path: '/login', //跳转到登陆页 query: { redirect: to.fullPath //登陆页须要知道从哪跳过来的,方便登陆成功后回到原页面 } }); } else { next(); } } else { next(); } }); ATT: next必定要执行否则钩子函数不会resolved。