vue--day89--路由守卫

发布时间 2023-09-17 00:38:28作者: 雪落无痕1

   ```js

   //全局前置守卫:初始化时执行、每次路由切换前执行

   router.beforeEach((to,from,next)=>{

   console.log('beforeEach',to,from)

   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'

   }

   })

   ```

 

4. 独享守卫:

 

   ```js

   beforeEnter(to,from,next){

   console.log('beforeEnter',to,from)

   if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制

   if(localStorage.getItem('school') === 'atguigu'){

   next()

   }else{

   alert('暂无权限查看')

   // next({name:'guanyu'})

   }

   }else{

   next()

   }

   }

   ```

 

5. 组件内守卫:

 

   ```js

   //进入守卫:通过路由规则,进入该组件时被调用

   beforeRouteEnter (to, from, next) {

   },

   //离开守卫:通过路由规则,离开该组件时被调用

   beforeRouteLeave (to, from, next) {

   }

   ```