路由守衛
-
作用:對路由進行權限控制
-
分類:全局守衛、獨享守衛、組件內守衛
-
全局守衛:
//全局前置守衛:初始化時執行、每次路由切換前執行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from,next) if(to.meta.isAuth){ //判斷當前路由是否需要進行權限控制 if(localStorage.getItem('school') === 'atguigu'){ //權限控制的具體規則 next() //放行 }else{ alert('暫無權限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守衛:初始化時執行、每次路由切換后執行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改網頁的title }else{ document.title = 'vue_test' } })
const Vr = new VueRouter({ routes: [ { name:'guanyu', path: '/about', component: About }, { name:'zhuye', path: '/home', component: Home, children:[ { name:'xiaoxi', path:'message', component:Message, // meta屬性用來給用戶自定義一些屬性 meta:{ isValidation:true }, children:[ { name:'msgQue', path:'messageQueue/:id/:title', component:MessageQueue, props($route){ return { id:$route.params.id, title:$route.params.title } } } ] }, { name:'xinwen', path:'news', meta:{ isValidation:true }, component:News } ] } ] }) Vr.beforeEach((to,from,next)=>{ //使用meta中用戶自定義的屬性來判斷是否需要路由檢驗 if(to.meta.isValidation){ if(localStorage.getItem('school') === '尚硅谷'){ next() }else{ alert('無權限') } }else{ next() } })