本教材由知了传课辛苦制作而成,仅供学习使用,请勿用于商业用途!如进行转载请务必注明出处!谢谢!

Vue-Router进阶

导航守卫:

导航守卫,就是导航过程中各个阶段的钩子函数。分为全局导航守卫路由导航守卫组件导航守卫。以下分别进行讲解。

全局导航守卫:

全局导航守卫,就是在整个网页中,只要发生了路由的变化,都会触发。全局导航守卫主要包括两个函数,分别为:beforeEachafterEach

beforeEach:

在路由发生了改变,但是还没有成功跳转的时候会调用。示例代码如下:

var router = new VueRouter({ routes: [ {path: "/",component: index,name:"index"}, {path: "/account",component: account,name:"account"}, {path: "/order",component: order,name:"order"}, {path: "/login",component: login,name:"login"}, ] }) router.beforeEach(function(to,from,next){ const authRoutes = ['account','order'] if(authRoutes.indexOf(to.name) >= 0){ if(logined){ next() }else{ next("/login") } }else if(to.name == 'login'){ if(logined){ next("/") } }else{ next() } })

afterEach:

路由已经改变完成后的函数。这个函数没有next参数。因为页面已经完成了跳转。

router.afterEach(function(to,from){ console.log('to:',to); console.log('from:',from); })

路由导航守卫:

路由组件导航守卫,也就是定义在路由上的导航守卫。使用方式就是在定义路由的对象中,传递一个beforeEnter参数。示例代码如下:

var router = new VueRouter({ routes: [ {path: "/login",component: login,name:"login",beforeEnter:function(to,from,next){ if(logined){ next("/") }else{ next() } }}, ] })

组件导航守卫:

组件导航守卫,就是在组件中写守卫。也就是进入到这个组件之前会调用的方法。组件导航守卫大体上也是三个方法:beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave。以下分别进行讲解。

beforeRouteEnter:

在进入到组件之前调用的。示例代码如下:

beforeRouteEnter(to,from,next){ // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 console.log('to:',to); console.log('from:',from); next(vm => { // 通过 `vm` 访问组件实例 console.log(vm.username); }) }

beforeRouteUpdate:

beforeRouteUpdate(to,from,next){ // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` console.log('to:',to); console.log('from:',from); next() }

beforeRouteLeave:

beforeRouteLeave(to,from,next){ // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` const answer = window.confirm('您确定要离开这个页面吗?') if (answer) { next() } else { next(false) } }

导航解析流程:

  1. 导航被触发。
  2. 在失活的组件里调用离开守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  5. 在路由配置里调用 beforeEnter。
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter。
  8. 调用全局的 beforeResolve 守卫 (2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

路由元信息:

在定义路由的时候,我们可以通过传递meta参数可以传递一些额外的信息。比如这个路由是需要登录后才能访问的,那么就可以在meta中添加一个requireAuth:true。示例代码如下:

let router = new VueRouter({ routes: [ {path: "/",component: index}, {path: "/profile/:userid",component: profile,meta:{requireAuth:true}}, {path: "/login",component: login} ] }) router.beforeEach(function(to,from,next){ if(to.meta.requireAuth && !logined){ next('/login') }else{ next() } })

589人已阅读,今天你学习了吗?

添加新回复