vue-router 提供的路由守卫主要用来通过跳转或取消的方式守卫路由,比如符合什么条件才可以进入路由,否则取消跳转,或者控制跳转路径,路由跳转成功过后需要做什么操作等等都可以使用路由守卫(路由钩子)实现,常用来做登录验证
全局守卫(全局前置守卫,全局解析守卫,全局后置钩子)
路由独享守卫
组件守卫
全局的守卫定义在main.js中
使用 router.beforeEach 注册一个全局前置守卫:
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
方法接收三个参数:
- to: 即将要进入的目标 路由对象
- from: 当前导航正要离开的路由 路由对象
- next : Function:确保要调用 next(),否则钩子就不会被 resolved。
next的几种使用:
使用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用
const router = new VueRouter({ ... })
router.beforeResolve ((to, from, next) => {
// ...
})
不会接受 next 函数也不会改变导航本身
router.afterEach((to, from) => {
// ...
})
在路由配置上直接定义 beforeEnter 守卫:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// 参数与全局前置守卫一致
}
}
]
})
export default {
name: "routerGuard",
data() {
return {}
},
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不能获取this,因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用,可以访问this
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用,可以访问this
}
}
参考官网:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html