导航守卫
vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。
有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。
全局守卫
- 全局前置守卫:router.beforeEach
- 全局解析守卫:router beforeResolve
- 全局后置钩子 router afterEach
全局前置守卫
当一个导航触发时就会触发全局前置守卫,所有的导航都会通过全局前置守卫
每个守卫方法接收三个参数:
to和from是将要进入和将要离开的路由对象,路由对象指的是平时通过this.$route获取到的路由对象。
next: Function: 钩子函数,里面定义参数,确认下一步路由要做什么
{
path: '/tuichu',
name: 'tuichu',
component: () => import('../views/login/Tuichu'),
meta: {
name: '主页',
//定义该页面是否需要登录,false表示不需要,true表示需要
isto: false
}
}
]
const router = new VueRouter({
routes
})
//全局前置守卫
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (token) {
return next();
} else {
if (!to.meta.isto) return next()
Toast('请登录')
}
//存在继续往后走
router.push({
name: 'codeLogin',
})
});
全局解析守卫
在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。
全局后置钩子
你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:
router.afterEach((to, from) => {
// ...
})
路由独享的守卫
你可以在路由配置上直接定义 beforeEnter 守卫:正如名字一样他时只针对一个路由的守卫如果要做登录判断token的话还是建议你使用router.beforeEach全局前置守卫
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
组件内的守卫
可以在路由组件内直接定义以下路由导航守卫:
进组组件前的守卫 beforeRouteEnter
路由更新时的守卫 beforeRouteUpdate (2.2 新增)
离开组件时的守卫 beforeRouteLeave
进组组件前的守卫
beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter (to, from, next) {
next(vm => {
vm.$store.state.token
// 通过 `vm` 访问组件实例
})
}
路由更新时的守卫
注意 beforeRouteEnter 是支持给 next 传递回调的唯一守卫。对于 beforeRouteUpdate 和 beforeRouteLeave 来说,this 已经可用了,所以不支持传递回调,因为没有必要了。
beforeRouteUpdate (to, from, next) {
// just use `this`
this.name = to.params.name
next()
}
离开组件时的守卫
这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
完整流程
1.导航被触发。
2.在失活的组件里调用 beforeRouteLeave 守卫。
3.调用全局的 beforeEach 守卫。
4.在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
5.在路由配置里调用 beforeEnter。
6.解析异步路由组件。
7.在被激活的组件里调用 beforeRouteEnter。
8.调用全局的 beforeResolve 守卫 (2.5+)。
9.导航被确认。
10.调用全局的 afterEach 钩子。
11.触发 DOM 更新。
12.调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。