路由守卫
当导航发生改变的时候,vue-router 会在多个不同的地方调用指定的函数,也就是与路由有关的生命周期函数,也称为:路由守卫
- 组件内守卫
- 路由独享守卫
- 全局守卫
组件内守卫
定义在组件内的与路由有关的生命周期函数(守卫)
- beforeRouteEnter
- beforeRouteUpdate
- beforeRouteLeave
beforeRouteEnter
当路由解析完成,并中指定的组件渲染之前(组件 beforeCreate
之前),不能这里通过 this
访问组件实例,需要通过 next
回调来进行调用
beforeRouteEnter (to, from, next) {
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
next(vm => {
// vm...
})
}
beforeRouteUpdate
在当前路由改变,但是该组件被复用时调用
beforeRouteUpdate(to,from,next){
console.log(to,from) //从哪里来,到哪里去
// 先要确认导航,然后做下面的事
next(); //next()表示true默认 next(false):不通过,将会跳转到to对应的路径 从哪里回哪去
// next('/path') 跳转指定路径
this.getItems() //然后执行下面功能
},
beforeRouteLeave
导航离开该组件的对应路由时调用
beforeRouteLeave (to, from, next) {
// 可以访问组件实例 `this`
}
to
即将要进入的目标 路由对象($route)
from
当前导航正要离开的路由对象($route)
next
路由确认回调函数,类似 Promise 中的 resolve 函数,一定要确保调用 next 函数,但是后续的导航行为将依赖 next 方法的调用参数
路由独享的守卫
可以在路由配置上直接定义 beforeEnter
守卫,相对来说,应用不多
注意:在理由里写是三个声明周期不加router
const router = new VueRouter(
{
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
}
)
全局守卫
全局守卫是注册在 router 对象(new VueRouter({…}))上的
- beforeEach
- beforeResolve
- afterEach
beforeEach
当一个导航触发时,全局前置守卫按照创建顺序调用
router.beforeEach((to, from, next) => {
// ...
})
beforeResolve
在所有组件内守卫和异步路由组件被解析之后被调用
router.beforeResolve((to, from, next) => {
// ...
})
afterEach
导航被确认后调用,因为导航已经被确认,所以没有 next
router.afterEach((to, from) => {
// ...
})