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