导航守卫
全局前置、后置守卫
使用 router.beforeEach
注册一个全局前置守卫:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// 一般在所有路由跳转之前检查token是否存在。
// console.log("to: ", to);
// console.log("from: ", from);
// next();
})
当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。
前置守卫都可传入三个参数:to, from, next。
to和from都是路由对象:
{
fullPath: "/",
hash: "",
matched: [{…}],
meta: {},
name: undefined,
params: {},
path: "/",
query: {},
}
路由独享守卫
在定义路由时:
const router = new VueRouter({
routes: [
{
path: '/a',
component: comA,
// 路由独享守卫
beforeEnter: (to, from, next) => {
console.log('I am A');
next();
}
},
{
path: '/b',
component: comB,
// 路由独享守卫
beforeEnter: (to, from, next) => {
console.log('I am B');
next();
}
}
]
})
组件内守卫
可以在路由组件内直接定义以下路由导航守卫:
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
const Foo = {
template: '...',
beforeRouteEnter(to, from, next) {
// 不能 获取组件实例 this
// 因为当该守卫执行时,组件实例还没被创建
// 此时传入next()函数的回调函数的第一个参数即为组件实例vm:
next((vm) => {
console.log(this === vm);
})
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 this
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 this
}
}