router 和 路由守衛(wèi)
路由配置
- 分模塊配置
- 404 配置
- 懶加載
- active-class
路由守衛(wèi)(跟 axios 攔截器有異曲同工之妙)
to 即將要進(jìn)入的目標(biāo) 路由對象
from 當(dāng)前導(dǎo)航正要離開的路由
-
next 一定要調(diào)用該方法來 resolve 這個鉤子。執(zhí)行效果依賴 next 方法的調(diào)用參數(shù)奋刽。
- next() 直接進(jìn)入進(jìn)行管道中的下一個鉤子
- next({ path: '/xxx' }) 跳轉(zhuǎn)到/xxx 路由
應(yīng)用
- 動態(tài)的給每個頁面添加 title
- 在某些路由頁面,比如我的訂單,購物車等需要登錄的頁面,判斷是否登錄,若沒登錄就跳到登錄頁面,
import Vue from "vue";
import Router from "vue-router";
import store from '../store/index';
Vue.use(Router);
const router = new Router({
routes: [{
path: "/",
redirect: "/index"
},
{
path: "/order",
meta: {
title: '我的訂單',
needLogin: true
},
component: () => import("@/views/order/index")
},
{
path: "/cart",
meta: {
title: '購物車',
needLogin: true
},
component: () => import("@/views/cart/index")
},
{
path: '/login',
component: () => import('@/views/login/index'),
meta: {
title: '登陸'
}
},
{
path: '/index',
component: () => import('@/views/index/index'),
meta: {
title: '首頁'
}
},
{
path: "/my",
component: () => import("@/views/my"),
redirect: '/my/center',
children: [{
path: 'center',
meta: {
title: '個人中心',
},
component: () => import('@/views/my/center')
}, {
path: 'set',
meta: {
title: '設(shè)置',
},
component: () => import('@/views/my/set')
}]
},
{
// 404配置
path: '*',
component: () => import('@/views/notFound')
}
]
});
router.beforeEach((to, from, next) => {
let {
title,
needLogin
} = to.meta;
// 從vuex獲取登錄狀態(tài)
let isLogin = store.state.isLogin;
document.title = title;
if (needLogin && !isLogin) {
next({
path: '/login'
})
} else {
next();
}
})
export default router;