Article Directory
1. Navigation guard
"Navigation" means that the routing is changing. The navigation guard provided by vue-router is mainly used to guard navigation by jumping or canceling.
There are three types of navigation guards:
- Global Navigation Guard
- Exclusive routing guard
- Guard in the component
2. Global navigation guard
1. Global front guard
It can be used router.beforeEach
to register a global front guard
const router = new VueRouter({
... })
router.beforeEach((to, from, next) => {
// ...
})
The guard method receives three parameters:
-
to
: Route, the route object of the target to be entered -
from
: Route, the route object that the current navigation is about to leave -
next
: Function, after calling this method, you can enter the next hook. next parameters have more usage, you can enter navigation guard | Vue Router official website detailed study
Use case, we can use beforeEach to complete the page title modification
const router = new VueRouter({
... })
router.beforeEach((to, from, next) => {
//从 from 跳转到 to
// document.title = to.meta.title;
document.title = to.matched[0].meta.title; //如果有嵌套路由,需要使用这种方式获取 meta中的数据
next();
})
2. Global rear guard
//没有 next 参数
router.afterEach((to, from) => {
// ...
})
Three, routing exclusive guard
It is the guard defined directly on the routing configuration
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
Fourth, the guard in the component
The following routing navigation guards can be defined directly in the routing component :
- beforeRouteEnter
- beforeRouteUpdate (2.2 新增)
- beforeRouteLeave
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
}