vue-router导航钩子

vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消

1、全局钩子

2、单个路由钩子

3、组件钩子

都必须要有 next() ,否则页面不会进行跳转

全局钩子:在每个页面切换的时候都会经过此钩子

// 注册一个全局钩子,防跳墙
router . beforeEach (( to , from , next ) => {
let token = localStorage . getItem ( 'mytoken' )
if ( token ) {
next ()
} else {
if ( to . path !== '/login' ) {
// 如果没有登录,但你访问其他需要登录的页面,那我就让你跳到登录页面去
next ({path: '/login' })
} else {
// 如果没有登录,但你访问的login,那就不干涉你,让你访问
next ()
}
}
})
// router.afterEach(route=> {
// // 此处没有next()
// console.log(this)
// })


单个路由钩子:写在单个路由配置上面

{
name: 'roles' ,
path: 'roles' ,
// 单个路由钩子
beforeEnter : ( to , form , next ) => {
console . log ( this )
},
component: Role
}


组件内钩子:写在组件内部

export default {
data (){
return {
}
},
methods: {
addGoods (){
this . $router . push ({name: 'addGoods' })
}
},
// 组件内钩子
beforeRouteEnter ( to , from , next ){
console . log ( this ) //undefined
//不能获取组件this,因为当钩子执行前组件实例还未创建
// next()
},
beforeRouteUpdate ( to , from , next ){
            //在当前路由改变,并且该组件复用时才调用
            //例如,对于一个带有参数的路径 /foo/:id, 当/foo/:1跳转到 /foo/2时候
            //此时foo组件,被复用,此时这个钩子会调用

console . log ( this )
next ()
},
beforeRouteLeave ( to , from , next ){
console . log ( this )
next ()
},
}


你可能感兴趣的:(vue)