VueRouter進階(2)-路由元信息

路由元信息

爲何會有這個東西呢?
咱們知道咱們瀏覽一些網站的時候有須要驗證登陸的也有不須要驗證登陸的,若是全部頁面都在作成驗證登陸的話對於用戶的體驗也是極差的,因此這個時候路由元信息就起到了很大的做用。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。
相關文章
相關標籤/搜索