美文网首页
特殊的动态权限路由实现总结

特殊的动态权限路由实现总结

作者: 爱代码的派派星 | 来源:发表于2021-10-06 00:02 被阅读0次

前段时间帮同事处理了一个小问题,趁十一得空总结下输出下,动态路由不是问题,场景是首个展示的页面就得去判断处理不同的权限路由并且最**的地方是由于项目的特殊性,需要俩个方法后才能确认权限(双异步,jsonp获取登陆状态及用户权限请求),用到的方法不是输出的重点,实现的方法才是重点,用到的几个关键点包含:

1、请求是promise是必然,方便后面书写处理addroute的逻辑 
2、router.getRoutes().length,判断是否已经添加上路由
3、执行下一步操作next()及next(to.path),  确保add结束再继续执行下一步
4、router.beforeEach当然也是必然的

代码思路如下

// 定义路由列表
const childList = [{},{}];

// 适配的路由
const otherList = {};

// 基准路由列表,一般指向home页
const routeList0 = [{
  path: '/home',
  name: 'Home',
  component: Home,
  redirect: '/yourRedirectPath',
  meta: {
    requiresAuth: yourRequiresAuth
  } 
}];

// 定义router
const router = new Router({
  mode: 'hash',
  routes: routeList0
})

// 第一个确认权限的promise
let casMetch = () => {...};

// 开始加路由
router.beforeEach((to, from ,next) => {
  if(可以开始添加路由的条件,如我的用户已经登陆并且获取到了权限类别) {
    if(我的权限 === 0) {
        if(router.getRoutes().length > 2) {
          next();
         } else {
          childList.map(item => {
            if(item === '需要判断添加不同路由的条件') {
              toAddRoute('名字');
            } else {
              router.addRoute('Home', item);
            }
          })
          router.addRoute(otherList);
          next();
      } else {      
        // 另一种权限的情况
        if (router.getRoutes().length > 2) {
          next();
        } else {
           childList.map(item => {
            if(item === '需要判断添加不同路由的条件') {
              toAddRoute('另一个添加的名字');
            } else {
              router.addRoute('Home', item);
            }
          })
          router.addRoute(otherList);
          next();
        }
      }
    }
  } else {
  // 没有获取到登陆信息时,获取俩个异步请求下的信息
  casMetch().then(()=> {  
    getUserDetail.then(() => {
        if(获取到的第一种权限情况) {
          if(router.getRoutes().length > 2) {
            next();
          } else {
            childList.map(item => {
                if(item.name == 'yourName') {
                  toAddroute('found');
                } else {
                  router.addRoute('Home', item);
                }
            })
            router.addRoute(otherList);
            next(to.path);
          }
        } else {  
           if(router.getRoutes().length > 2) {
              next();
           } else {
                childList.map(item => {
                if(item.name == 'yourOtherName') {
                  toAddroute('found2');
                } else {
                  router.addRoute('Home', item);
                }
            })
            router.addRoute(otherList);
            next(to.path);
           }
        }
    })
  })
  }
})

export default router

相关文章

网友评论

      本文标题:特殊的动态权限路由实现总结

      本文链接:https://www.haomeiwen.com/subject/ezrnnltx.html