爲何會有路由元信息這個東西?數組
咱們在作網站登陸驗證的時候,可使用到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()
})