前言:
本篇博客是从本人在博客园写的搬过来的,和第18篇有些许重复,重复的就当复习了,没重复的就补充一下吧。
路由钩子,即导航钩子,其实就是路由拦截器。vue-router一共有3类:
1.全局钩子(最常用)
2.路由单独钩子
3.组件内钩子
1.全局钩子
// 定义路由配置
const router = new VueRouter({ ... })
// 全局路由拦截-进入页面前执行
router.beforeEach((to, from, next) => {
// 这里可以加入全局登录判断
// 继续执行
next();
});
// 全局后置钩子-常用于结束动画等
router.afterEach(() => {
//不接受next
});
export default router;
每个钩子方法接收三个参数:
to: Route : 即将要进入的目标 [路由对象]
from: Route : 当前导航正要离开的路由
next: Function : 继续执行函数
-
next():继续执行
-
next(false):中断当前的导航。
-
next(‘/‘) 或 next({ path: ‘/‘ }):跳转新页面,常用于登录失效跳转登录
2.路由单独钩子
在路由配置中单独加入钩子:
{
path:'/home/one', // 子页面1
component: One,
// 路由内钩子
beforeEnter: (to, from, next) => {
console.log('进入前执行');
next();
}
}
3.组件内钩子
使用:在路由组件内定义钩子函数:
- beforeRouteEnter:进入页面前调用
- beforeRouteUpdate (2.2 新增):页面路由改变时调用,一般需要带参数
- beforeRouteLeave:离开页面调用
<script>
export default {
name: 'Two',
data () {
return {
msg: 'Hi, I am Two Page!'
}
},
// 进入页面前调用
beforeRouteEnter(to, from, next) {
console.log('进入enter路由钩子')
next()
},
// 离开页面调用
beforeRouteLeave(to,from, next){
console.log('进入leave路由钩子')
next()
},
// 页面路由改变时调用
beforeRouteUpdate(to, from, next) {
console.log('进入update路由钩子')
console.log(to.params.id)
next()
}
}
</script>