为何会有路由元信息这个东西?数组
咱们在作网站登陆验证的时候,可使用到beforeEach 钩子函数进行验证操做,以下面代码 ,若是页面path为’/goodsList’,那么就让它跳转到登陆页面,实现了验证登陆。函数
1 router.beforeEach((to, from, next) => { 2 if (to.path === '/goodsList') { 3 next('/login') 4 } else 5 next() 6 })
若是须要登陆验证的网页多了怎么办?网站
1.这里是对比path。若是须要验证的网页不少,那么在if条件里得写下全部的路由地址,将会是很是麻烦的一件事情。ui
2.由于路由是能够嵌套的。有’/goodsList’,那么可能会有’/goodsList/online’,再或者还有’/goodsList/offline’、’/goodsList/audit’、’/goodsList/online/edit’等等。spa
若是像刚才例子中这样对比(to.path === ‘/goodsList’),就很是单一,其余的路径压根不会限制(验证)到,照样能正常登录!由于每一个to.path根本不同。code
咱们所理想的就是把’/goodsList’限制了,其余全部的以’/goodsList’开头的那些页面都给限制到!component
to Route: 即将要进入的目标 路由对象
咱们打印一下torouter
它有不少属性,有
- fullPath
- hash
- matched
- meta
- name
- params
- path
- query对象
其中有个属性,matched,就是匹配了的路由,咱们打印出来,这个是个数组。它的第一项就是{path: “/goodslist”},一直到最为具体的当前path (例如:{path: “/goodslist/online/edit”})blog
这里能够循环matched这个数组,看每一项的path 有没有等于’/goodsList’,只要其中一个有,那么就让它跳转到登陆状态
router.beforeEach((to, from, next) => {
if (to.matched.some(function (item) {
return item.path == '/goodslist'
})) {
next('/login')
} else
next()
})
那么这里只是对goodsList进行验证判断,且限制的仍是path,若是页面中还有会员列表、资讯列表、广告列表都须要进行验证的时候,用path来作限制彷佛有点很差用。轮到主角登场了
meta字段(元数据)
直接在路由配置的时候,给每一个路由添加一个自定义的meta对象,在meta对象中能够设置一些状态,来进行一些操做。用它来作登陆校验再合适不过了
{
path: '/actile',
name: 'Actile',
component: Actile,
meta: {
login_require: false
},
},
{
path: '/goodslist',
name: 'goodslist',
component: Goodslist,
meta: {
login_require: true
},
children:[
{
path: 'online',
component: GoodslistOnline
}
]
}
这里咱们只须要判断item下面的meta对象中的login_require是否是true,就能够作一些限制了
router.beforeEach((to, from, next) => {
if (to.matched.some(function (item) {
return item.meta.login_require
})) {
next('/login')
} else
next()
})