Vue中的导航守卫(路由守卫)

当做Vue-cli项目的时候感觉在路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。
对此,vue-router 提供的 beforeEach可以方便地实现全局导航守卫(navigation-guards)。组件内部的导航守卫函数使用相同,只是函数名称不同(beforeRouteEnter 、beforeRouteUpdate(2.2 新增) 、beforeRouteLeave)。

官方文档地址:https://router.vuejs.org/zh-cn/advanced/navigation-guards.html

如何设置一个全局守卫

你可以使用 router.beforeEach 注册一个全局前置守卫:就是在你router配置的下方注册

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中

每个守卫方法接收三个参数:

  • to: Route: 即将要进入的目标 路由对象

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

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

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

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

    • next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: truename: 'home' 之类的选项以及任何用在 router-linkto proprouter.push 中的选项。

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

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

一个简单实用的小例子:

const router = new VueRouter({ ... }) //这是路由配置,我就不多说了

const whiteList = ['/error', '/register/regindex', '/register/userauthent',  '/register/submit'] // 路由白名单
vueRouter.beforeEach(function(to,from,next){
    console.log("进入守卫");
    if (userInfo.user_id>0){
        console.log("登录成功");
        next();   //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
    }else{
        console.log("登录失败");
        getUserInfo.then(res => {
            if(res){
                if (res.user_id){
                    if (res.status == 4) {
                        //账号冻结
                        next({ path: '/error', replace: true, query: { noGoBack: true } })
                    }
                    if (res.status == 3) {
                        //认证审核中
                        next({ path: '/register/submit', replace: true, query: { noGoBack: true } })
                    }
                    if (res.status != 1 && res.status != 3) {
                        if (!res.mobile ) {
                            next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
                        } else {
                            //绑定完手机号了
                            next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } })
                        }
                    }
                    next();  //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
                }else{
                    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
                        next();  //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
                    }else{
                        next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
                    } 
                }
                
            }else{
                
                }
            }
            
        }).catch(()=>{
            //跳转失败页面
            next({ path: '/error', replace: true, query: { noGoBack: true }})
        })
    }
    
    
});

export default router

温馨提示:有些地方为vuex介入调取方法及数据判断,但由于例子原因就不展示,只提供思路供大家参考。

最后和大家说下如果白名单太多或项目更大时,我们需要把白名单换为vue-router路由元信息:

meta字段(元数据)

直接在路由配置的时候,给每个路由添加一个自定义的meta对象,在meta对象中可以设置一些状态,来进行一些操作。用它来做登录校验再合适不过了

{
  path: '/actile',
  name: 'Actile',
  component: Actile,
  meta: {
    login_require: false
  },
},
{
  path: '/goodslist',
  name: 'goodslist',
  component: Goodslist,
  meta: {
    login_require: true
  },
  children:[
    {
      path: 'online',
      component: GoodslistOnline
    }
  ]
}

这里我们只需要判断item下面的meta对象中的login_require是不是true,就可以做一些限制了

router.beforeEach((to, from, next) => {
  if (to.matched.some(function (item) {
    return item.meta.login_require
  })) {
    next('/login')
  } else 
    next()
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vue-Router简介 Vue-Router是Vue.js官方维护的路由插件,同时也是官方推荐的路由插件。它与V...
    SunnySky_阅读 852评论 0 1
  • vue2有着深度继承的路由插件,即:vue-router,其中文的API地址。 vue-router与其他的路由(...
    白水螺丝阅读 17,550评论 0 17
  • vue-router学习笔记 安装 并且如果在一个模块化工程中使用它,必须要通过Vue.use()明确地安装路由功...
    EL_PSY_CONGROO阅读 593评论 0 0
  • 响应路由参数的变化 v-router提供的导航守卫主要用来通过跳转或者取消的方式守卫导航。有多种机会植入路由导航过...
    Gopal阅读 660评论 0 0
  • vue-cli搭建项目 确保安装了node与npm 再目标文件夹下打开终端 执行cnpm i vue-cli -g...
    Akiko_秋子阅读 3,264评论 1 22