路由守卫
-
作用:对路由进行权限控制
-
分类:全局守卫、独享守卫、组件内守卫
-
全局守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行 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() } })