路由钩子分为三种
- 全局钩子: beforeEach、 afterEach、beforeResolve
- 单个路由里面的钩子: beforeEnter
- 组件路由:beforeRouteEnter、 beforeRouteUpdate、 beforeRouteLeave
它的三个参数:
to: (Route路由对象) 即将要进入的目标 路由对象 to对象下面的属性: path params query hash fullPath matched name meta(在matched下,但是本例可以直接用)
from: (Route路由对象) 当前导航正要离开的路由
next: (Function函数) 一定要调用该方法来 resolve 这个钩子。 调用方法:next(参数或者空) ***必须调用
next(无参数的时候): 进行管道中的下一个钩子,如果走到最后一个钩子函数,那么 导航的状态就是 confirmed (确认的)
全局钩子
- beforeEach: 页面加载之前
- afterEach: 页面加载之后
- beforeResolve: 用的比较少,和beforeEach类似
router.beforeEach((to,from,next) => {
console.log('beforeEach ===',to,from)
next()
})
router.beforeResolve((to,from,next) => {
console.log('beforeResolve ===',to,from)
next()
})
router.afterEach((to,from) => {
console.log('afterEach ===',to,from)
})
路由独享守卫
beforeEnter: 路由配置上直接定义 beforeEnter 守卫
{
path: '/',
name: 'Home',
component: Home,
beforeEnter: (to,from,next) => {
console.log('beforeEnter ==', to,from)
next()
}
}
路由组件内的守卫
- beforeEach:在渲染该组件的对应路由被 confirm 前调用
- afterEach: 当前路由改变,但是该组件被复用时调用
- beforeResolve: 导航离开该组件的对应路由时调用
beforeRouteEnter: (to,from,next) => {
console.log('beforeRouteEnter ==', to,from)
next()
},
beforeRouteUpdate: (to,from,next) => {
console.log('beforeRouteUpdate ==', to,from)
next()
},
beforeRouteLeave: (to,from,next) => {
console.log('beforeRouteLeave ==', to,from)
next()
},
路由执行顺序
|