Vue 2.x – 两个新的生命周期钩子/路由守卫

11.两个新的生命周期钩子

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
  2. 具体名字:
    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。

12.路由守卫

  1. 作用:对路由进行权限控制

  2. 分类:全局守卫、独享守卫、组件内守卫

  3. 全局守卫:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    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. 独享守卫:

    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) {
    }

代码

https://github.com/icrons/Vue-Learn/tree/master/39_src_%E4%B8%A4%E4%B8%AA%E6%96%B0%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90

https://github.com/icrons/Vue-Learn/tree/master/40_src_%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E8%B7%AF%E7%94%B1%E5%AE%88%E5%8D%AB

https://github.com/icrons/Vue-Learn/tree/master/41_src_%E5%85%A8%E5%B1%80%E5%90%8E%E7%BD%AE%E8%B7%AF%E7%94%B1%E5%AE%88%E5%8D%AB

https://github.com/icrons/Vue-Learn/tree/master/42_src_%E7%8B%AC%E4%BA%AB%E8%B7%AF%E7%94%B1%E5%AE%88%E5%8D%AB

https://github.com/icrons/Vue-Learn/tree/master/43_src_%E7%BB%84%E4%BB%B6%E5%86%85%E8%B7%AF%E7%94%B1%E5%AE%88%E5%8D%AB

版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/145.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Vue 2.x – 两个新的生命周期钩子/路由守卫
11.两个新的生命周期钩子 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。 具体名字: activated路由组件被激活时触发。 deactivated路由组……
<<上一篇
下一篇>>