路由拦截

  1. 路由守卫可以做什么???
    借助于VueRouter的钩子函数beforeEach,判断是否有权限进入,执行next()或next(false)
    router.beforeEach((to, from ,next) => {
    // next() 通过,允许进入
    // next(false) 禁止,不允许进入该模块
    })
  2. 路由配置
router.beforeEach((to, from ,next) => {
// next() 通过,允许进入
// next(false) 禁止,不允许进入该模块
})

在VueRouter的路由配置项中,增加meta属性,设置是否需要权限验证的标记

  {
    path: 'user',
    name: 'User',
    Component: User,
    meta: {
        // 需要权限验证
        requireAuth: true
    }
  }
  1. 判断有没有权限进入页面
   const router = new VueRouter({
       routes: [
           // ...
       ]
   })      
   // 权限拦截-beforeEach路由钩子函数
   router.beforeEach (to, from, next) {
       // to 目的路由对象 from 来源路由对象
       if (to.match.some(rocode => recode.meta.requireAuth)) {
           /**
           * 登录状态-可使用aixos进行请求,拉取服务器数据,获取用户登录状态
           * 在本地使用localStorage或sessionStorage和vuex共同管理用户登录态
           * 如果已登录,则更新store中存储的loginName
           * 未登录,则直接跳转走
           */ 
           let isLogin = 已登录 ? true : false
           // 执行拦截判定
           if (!isLogin) {
               // 跳转到登录模块
               // next()方法
               next({
                   name: 'Login',
                   replace: 'true',
                   // redirectUrl 用于标记登录后回跳的地址
                   redirectUrl: to.fullPath
               })
               
               
           } else {
               // 已登录,直接进入
               next()
           }    
       } else {
           // 不执行拦截,直接进入该路由
           next()
       }
   }   

你可能感兴趣的:(路由拦截)