最近学习一下,vue-router的路由钩子函数,相信只要学前端的小伙伴都接触的很多,在这里简单汇总一下,但愿对小伙伴們有所帮助。
路由钩子函数分为三种类型以下:
第一种:全局钩子函数。
router.beforeEach((to, from, next) => {
console.log('beforeEach')
//next() //若是要跳转的话,必定要写上next()
//next(false) //取消了导航
next() //正常跳转,不写的话,不会跳转
})
router.afterEach((to, from) => { // 举例: 经过跳转后改变document.title
if( to.meta.title ){
window.document.title = to.meta.title //每一个路由下title
}else{
window.document.title = '默认的title'
}
})
第二种:针对单个路由钩子函数
beforeEnter(to, from, next){
console.log('beforeEnter')
next() //正常跳转,不写的话,不会跳转
}
第三种:组件级钩子函数
beforeRouteEnter(to, from, next){ // 这个路由钩子函数比生命周期beforeCreate函数先执行,因此this实例尚未建立出来
console.log("beforeRouteEnter")
console.log(this) //这时this仍是undefinde,由于这个时候this实例尚未建立出来
next((vm) => { //vm,能够这个vm这个参数来获取this实例,接着就能够作修改了
vm.text = '改变了'
})
},
beforeRouteUpdate(to, from, next){//能够解决二级导航时,页面只渲染一次的问题,也就是导航是否更新了,是否须要更新
console.log('beforeRouteUpdate')
next();
},
beforeRouteLeave(to, from, next){// 当离开组件时,是否容许离开
next()
}前端