路由守卫
vue-router
提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。
分为三种:全局守卫、路由独享守卫、组件内守卫
全局守卫
在router.js
中
const router = new VueRouter({... })router.beforeEach((to, from, next) => {// to 将要去的路由对象// from 从那个路由对象来的// next 是否继续执行if (to.name == 'Login' && localStroag.getItem("token")) next()// 如果用户未能验证身份,则 `next` 会被调用两次next({name: 'Login' })})
路由独享守卫:你可以在路由配置上直接定义beforeEnter
守卫:
const router = new VueRouter({routes: [{path: '/foo',component: Foo,beforeEnter: (to, from, next) => {// ...if (to.name == 'Login' && localStroag.getItem("token")) next()// 如果用户未能验证身份,则 `next` 会被调用两次next({name: 'Login' })}}]})
组件内守卫
在组件内部定义,和data/methods/mounted同级
beforeRouteEnter
beforeRouteUpdate
(2.2 新增)beforeRouteLeave
const Foo = {template: `...`,beforeRouteEnter (to, from, next) {if (to.name == 'Login' && localStroag.getItem("token")) next()// 如果用户未能验证身份,则 `next` 会被调用两次next({name: 'Login' })}// 在渲染该组件的对应路由被 confirm 前调用// 不!能!获取组件实例 `this`// 因为当守卫执行前,组件实例还没被创建},beforeRouteUpdate (to, from, next) {// 在当前路由改变,但是该组件被复用时调用// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。// 可以访问组件实例 `this`},beforeRouteLeave (to, from, next) {// 导航离开该组件的对应路由时调用// 可以访问组件实例 `this`}}
beforeRouteEnter
守卫不能访问this
,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。
不过,你可以通过传一个回调给next
来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter (to, from, next) {next(vm => {// 通过 `vm` 访问组件实例})}
完整的导航解析流程
导航被触发。在失活的组件里调用 beforeRouteLeave 守卫。调用全局的 beforeEach 守卫。在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。在路由配置里调用 beforeEnter。解析异步路由组件。在被激活的组件里调用 beforeRouteEnter。调用全局的 beforeResolve 守卫 (2.5+)。导航被确认。调用全局的 afterEach 钩子。触发 DOM 更新。调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。如果觉得《vue-router路由守卫》对你有帮助,请点赞、收藏,并留下你的观点哦!