用 vue-route 的 beforeEach 实现导航守卫(路由跳转前验证登录)

路由跳转前做一些验证,比如登录验证(未登录去登录页),是网站中的普遍需求。对此,vue-route 提供的 beforeRouteUpdate 可以方便地实现导航守卫(navigation-guards)。
导航守卫(navigation-guards)这个名字,听起来怪怪的,但既然官方文档是这样翻译的,就姑且这么叫吧。
贴上文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html

先来摘抄一段文档中beforeRouteUpdate 的用法:
你可以使用 router.beforeEach 注册一个全局前置守卫:
[javascript]  view plain  copy
  1. const router = new VueRouter({ ... })  
  2.   
  3. router.beforeEach((to, from, next) => {  
  4.   // ...  
  5. })  

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。
每个守卫方法接收三个参数:
    • to: Route: 即将要进入的目标 路由对象

    • from: Route: 当前导航正要离开的路由

    • next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

      • next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

      • next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

      • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

      • next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。

下面写一个例子,上一篇博客中我们的账户页,包括课程和订单,都需要在跳转前判断是不是已登录; 已登录的情况再去登录页,跳转至首页:
[javascript]  view plain  copy
  1. const vueRouter = new Router({  
  2.     routes: [  
  3.         //......  
  4.         {  
  5.           path: '/account',  
  6.           name: 'account',  
  7.           component: Account,  
  8.           children: [  
  9.             {name: 'course', path: 'course', component: CourseList},  
  10.             {name: 'order', path: 'order', component: OrderList}  
  11.           ]  
  12.         }  
  13.     ]  
  14. });  
  15. vueRouter.beforeEach(function (to, from, next) {  
  16.     const nextRoute = [ 'account''order''course'];  
  17.     const auth = store.state.auth;  
  18.     //跳转至上述3个页面  
  19.     if (nextRoute.indexOf(to.name) >= 0) {  
  20.         //未登录  
  21.         if (!store.state.auth.IsLogin) {  
  22.             vueRouter.push({name: 'login'})  
  23.         }  
  24.     }  
  25.     //已登录的情况再去登录页,跳转至首页  
  26.     if (to.name === 'login') {  
  27.         if (auth.IsLogin) {  
  28.             vueRouter.push({name: 'home'});  
  29.         }  
  30.     }  
  31.     next();  
  32. });  

猜你喜欢

转载自blog.csdn.net/beichen3997/article/details/80701730