• vue 动态添加路由及部分权限


    // 菜单模块
    let newRoutes = [
      {
        path: '/',
        redirect: '/home',
        component: resolve => require(['../components/common/Home.vue'], resolve),
        meta: {
          title: '/',
          requiresAuth: true
        },
        children: [
          {
            path: '/home',
            component: resolve => require(['../components/page/home.vue'], resolve),
            meta: {title: '首页', requiresAuth: true}
          },
          {
            path: '/building',
            component: resolve => require(['../components/page/buiding.vue'], resolve),
            meta: {
              title: '构建中',
              requiresAuth: false
            }
          }
        ]
      }
    ]
    
    // 静态路由
    let router = new Router({
      // mode: 'history',
      routes: [
        {
          path: '/login',
          component: resolve => require(['../components/page/login.vue'], resolve),
          meta: {
            title: '登录',
            requiresAuth: false
          }
        },
        {
          path: '/404',
          component: resolve => require(['../components/page/404.vue'], resolve),
          meta: {
            title: '404',
            requiresAuth: false
          }
        }
      ]
    })
    // 声明白名单
    let arr = []
    // 登录拦截器
    router.beforeEach((to, from, next) => {
    let isLogin = localStorage.getItem('uid')
    // 判断该路由是否需要登录权限 if (to.matched.some(record => record.meta.requiresAuth)) { if (isLogin) { next() } else { return next({path: '/login' }) } } else { next() } // 判断第一次登录页面的时候 及 刷新页面的时候 if ( (to.path == '/home' && from.path == '/login' && localStorage.getItem('uid')) || to.meta.requiresAuth==undefined) { // 获取路由,请求数据 getMenu().then((res) => { localStorage.setItem('menuList',window.btoa(window.encodeURIComponent(JSON.stringify(res)))) // 菜单模块 res.forEach(e=>{ e.children.forEach(i=>{ arr.push(i.paht) // 将路由存入白名单 newRoutes[0].children.push({ path: i.path, component: resolve => require(['../components/page/'+ i.str +'.vue'], resolve), meta: { title: i.elementLabel, requiresAuth: true, params: i.children } }) }) }) // 添加路由 router.addRoutes(newRoutes) localStorage.setItem('newRoutes', window.btoa(window.encodeURIComponent(newRoutes))) // 匹配白名单 if ((arr.indexOf(to.path)>=0)&
    &to.path!='/building') { next() } else { next('/home') } }) } if (to.matched.length ===0) { // 如果未匹配到路由 if (!localStorage.getItem('uid')) { next('/login') } } else { // 如果匹配到正确跳转 next() } }) // 路由报错 router.onError(error => { // 已有路由未配置页面文件的情况下 router.push('/building') })
  • 相关阅读:
    程序员面视题解析
    Forms身份验证
    梅花雨日历控件
    系统架构师学习笔记_第四章(下)
    系统架构师学习笔记_第三章
    系统架构师学习笔记_第六章(上)
    系统架构师学习笔记_第五章(下)
    系统架构师学习笔记_第一章
    系统架构师学习笔记_第四章(上)
    系统架构师学习笔记_第五章(上)
  • 原文地址:https://www.cnblogs.com/chloey/p/10233022.html
Copyright © 2020-2023  润新知