vue路由鉤子大致可以分為三類:
1.全局鉤子
主要包括beforeEach和aftrEach,
????beforeEach函數(shù)有三個參數(shù):
to:router即將進(jìn)入的路由對象
from:當(dāng)前導(dǎo)航即將離開的路由
next:Function,進(jìn)行管道中的一個鉤子溃列,如果執(zhí)行完了挥唠,則導(dǎo)航的狀態(tài)就是 confirmed (確認(rèn)的)斯撮;否則為false,終止導(dǎo)航。
????afterEach函數(shù)不用傳next()函數(shù)
這類鉤子主要作用于全局,一般用來判斷權(quán)限,以及以及頁面丟失時候需要執(zhí)行的操作,例如:
//使用鉤子函數(shù)對路由進(jìn)行權(quán)限跳轉(zhuǎn)
router.beforeEach((to, from, next) => {
? ? const role = localStorage.getItem('ms_username');
? ? if(!role && to.path !== '/login'){
? ? ? ? next('/login');
? ? }else if(to.meta.permission){
? ? ? ? // 如果是管理員權(quán)限則可進(jìn)入轧葛,這里只是簡單的模擬管理員權(quán)限而已
? ? ? ? role === 'admin' ? next() : next('/403');
? ? }else{
? ? ? ? // 簡單的判斷IE10及以下不進(jìn)入富文本編輯器,該組件不兼容
? ? ? ? if(navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor'){
? ? ? ? ? ? Vue.prototype.$alert('vue-quill-editor組件不兼容IE10及以下瀏覽器,請使用更高版本的瀏
????????????覽器查看', '瀏覽器不兼容通知', {
? ? ? ? ? ? ? ? confirmButtonText: '確定'
? ? ? ? ? ? });
? ? ? ? }else{
? ? ? ? ? ? next();
? ? ? ? }
? ? }
})
2.單個路由里面的鉤子
主要用于寫某個指定路由跳轉(zhuǎn)時需要執(zhí)行的邏輯
??????????????{
? ? ? ? ? ? ? ? ? ? path: '/dashboard',
? ? ? ? ? ? ? ? ? ? component: resolve => require(['../components/page/Dashboard.vue'], resolve),
? ? ? ? ? ? ? ? ? ? meta: { title: '系統(tǒng)首頁' },
? ? ? ? ? ? ? ? ? ? beforeEnter: (to, from, next) => {
? ? ? ? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? ? ? beforeLeave: (to, from, next) => {
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? },
3.組件路由
? ? 主要包括?beforeRouteEnter和beforeRouteUpdate?,beforeRouteLeave,這幾個鉤子都是寫在組件里面也可以傳三個參數(shù)(to,from,next),作用與前面類似.