Vue路由钩子

765 阅读1分钟

1. 全局钩子

beforeEach和afterEach

注意:每次路由跳转都会执行beforeEach和afterEach

beforeEach有三个参数:to、from,next

afterEach有两个参数:to、from

举例:beforeEach (判断是否登录了,没登录就跳转到登录页)

router.beforeEach((to, from, next) => {  
    let ifInfo = Vue.prototype.$common.getSession('userData');  // 判断是否登录的存储信息
    if (!ifInfo) { 
        // sessionStorage里没有储存user信息    
        if (to.path == '/') { 
            //如果是登录页面路径,就直接next()      
            next();    
        } else { 
            //不然就跳转到登录      
            Message.warning("请重新登录!");     
            window.location.href = Vue.prototype.$loginUrl;    
        }  
    } else {    
        return next();  
    }
})

举例:afterEach(跳转之后滚动条返回顶部)

router.afterEach((to, from) => {  
    // 跳转之后滚动条回到顶部  
    window.scrollTo(0,0);
});


2. 单个路由独享钩子

beforeEnter有三个参数:to、from、next

export default [    
    {        
        path: '/',        
        name: 'login',        
        component: login,        
        beforeEnter: (to, from, next) => {          
            console.log('即将进入登录页面')          
            next()        
        }    
    }
]


3. 组件内的钩子

beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave

这三个钩子都有三个参数:to、from、next

beforeRouteEnter:进入组件前触发

beforeRouteUpdate:当前地址改变并且改组件被复用时触发,举例来说,带有动态参数的路径foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,由于会渲染同样的foo组件,这个钩子在这种情况下就会被调用

beforeRouteLeave:离开组件被调用

注意点,beforeRouteEnter组件内还访问不到this,因为该守卫执行前组件实例还没有被创建,需要传一个回调给next来访问,例如

beforeRouteEnter(to, from, next) {      
    next(target => {        
        if (from.path == '/classProcess') {          
            target.isFromProcess = true        
        }      
    })    
}

beforeRouteUpdate和beforeRouteLeave可以访问组件实例this