路由守衛(wèi)
路由文件基礎配置
import VueRouter from "vue-router";
import About from '@/pages/About.vue'
import Home from "@/pages/Home.vue";
import Message from "@/pages/Message.vue";
import News from "@/pages/News.vue";
import Detail from "@/pages/Detail.vue";
const router= new VueRouter({
routes: [
{
name: 'ABout',
path: '/about',
component: About,
meta:{title:'關于'}
},
{
path: '/home',
name:'HOme',
component: Home,
meta:{title:'主頁'},
children: [
{
path: 'message',
name:'MEssage',
component: Message,
meta:{isAuth:true,title:'消息'},
children: [
{
name: 'DEtail',
path: 'detail',
component: Detail,
meta:{isAuth:true,title:'詳情'},
props($route){
return {
id:$route.query.id,
title:$route.query.title
}
}
}
]
},
{
name: 'NEws',
path: 'news',
component: News,
meta:{isAuth:true,title:'新聞'}
}
]
},
]
})
export default router
作用:通過跳轉或取消的方式守衛(wèi)導航,對路由進行權限控制
分類:全局守衛(wèi)、獨享守衛(wèi)、組件內(nèi)守衛(wèi)
全局守衛(wèi)
前置守衛(wèi)
作用時機:初始化、每次路由切換前執(zhí)行
-
實現(xiàn):
-
初始鑒權方式
router.beforeEach((to, from, next)=>{ if (to.name==='NEws' || to.name==='MEssage'){ if (localStorage.getItem('name')==='test'){ next() } }else { next() } }) -
使用路由元信息進行鑒權
router.beforeEach((to, from, next)=>{ // 是否需要鑒權 if (to.meta.isAuth){ if (localStorage.getItem('name')==='test'){ next() } }else { next() } })
-
后置守衛(wèi)
作用時機:初始化、每次路由切換后執(zhí)行
-
實現(xiàn)
router.afterEach((to,from)=>{ document.title=to.meta.title|| '開始' })