vue学习---vue-router路由守卫 (全局前置守卫,全局后置首位) 路由中meta属性


路由守卫

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

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

  3. 全局守卫:

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM