钩子函数

  1. 全局钩子函数

    beforeEach、afterEach

  2. 路由独享的钩子函数

    beforeEnter

  3. 组件内钩子函数

    beforeRouterEnter、beforeRouterUpdate、beforeRouterLeave

全局钩子函数

beforeEach

参数:

to:即将进入的路由对象
from:正要离开的路由对象
next:路由的控制参数

next() 调用方式:

  1. next()

    一切正常调用进入下一个钩子

  2. next(false)

    取消路由导航,返回正要离开的路由地址

  3. next(‘/path’)

    当前路由终止,页面重定向

  4. next(error)

    路由导航终止并且错误会被传递到 router.onError() 注册过的回调中

应用场景:登录权限,页面权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 进入路由前钩子
router.beforeEach((to, from, next) => {
/*
to 目标路由
from 源路由
next 跳转到下一个路由
*/

if (window.localstorange.getItem("token")) {
// 如果存在,则直接跳转到对应路由
next();
} else {
// 如果不存在,则跳转到登录页
next('/login');
}
});

afterEach

参数:

to:即将进入的路由对象
from:正要离开的路由对象

应用场景:

重置页面滚动条位置
1
2
3
4
router.afterEach((to, from) => {
//将滚动条恢复到最顶端
window.scrollTo(0, 0);
})

路由独享的钩子函数

beforeEneter

在路由配置中添加key—value
1
2
3
4
5
6
7
8
9
10
11
12
const routes=[
{
path:'/path',
component:page1,
...
//路由独享的钩子函数
beforeEnter:(to,from,next)=>{
console.log(to);
console.log(from);
next(false);
}
}

组件内钩子函数

beforeRouteEnter(to,from,next)

路由进入前调用,此时 Vue 实例未创建,所有唯一不能使用 this 的钩子函数

beforeRouteUpdate(to,from,next)

路由发生修改的时候进行调用

beforeRouteLeave(to,from,next)

路由离开该组件时调用

使用方法:

组件中添加 `方法`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export default {
//路由进入前调用
beforeRouteEnter (to, from, next) {
next();
},
//路由修改时调用
beforeRouteUpdate(to,from,next){

},
//路由离开时调用
beforeRouteLeave(to,from,next){

},
data () {
return {
msg: "我是组件"
}
}
}