JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue路由守卫

2019. 06. 09    

主要介绍几种Vue路由守的方式

全局守卫

    //to 要跳转的页面  from 要离开的组件  next 下一步执行
    router.beforeEach((to, from, next) => {
        if(to.path == '/login' || to.path == '/register'){
            next()
        }else{
            alert('还没有登录')
            next('/lodin')
        }
    })


独享守卫

    //原理同上 只给单独页面设置守卫
    {path: '/admin',name: 'admin',component: Admin,beforeEnter: (to, from, next) => {
        //alert('非登录状态,不能访问')
        //next('/login')
        if(to.path == '/login' || to.path == '/register'){
            next()
        }else{
            alert('还没有登录')
            next('/lodin')
        }
    }}


组件内的守卫

Admin.vue 内部

    <template>
    .....
    </template>
    <script>
        export default{
            data(){
                return{
                    name: 'Henry'
                }
            },
            beforeRouteEnter (to, from, next) => {
                //alert(`hello ${this.name}`) //hello undefal
                next(vm => {
                    alert(`hello ${this.name}`)
                })
            },
            beforeRouteLeave (to, from, next) => {
                if(confirm('确定要离开吗') == true){
                    next()
                }else{
                    next false;
                }
            
            },
        
        }
    </script>

以上