vue-element-admin前端框架实现动态路由

vue-element-admin前端框架实现动态路由

  • 1.获取用户权限信息
  • 2.根据权限信息生成路由的json串
  • 3.触发动态路由的生成

1.获取用户权限信息

从用户登录后的response中获取用户的权限信息,存放在stroe中。
关键代码:/src/store/user.js

const actions = {
  // 登录并返回user信息
  login({ commit }, userInfo) {
    const { code, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ code: code.trim(), password: password }).then(response => {
        commit('SET_AUTH', response.head.message)
        commit('SET_NAME', response.body.name)
        commit('SET_RESOURCES',getResource(response.body.roles))
        commit('SET_INFO',response.body)
        setAuth(response.message)
        setUseInfo(code,password)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
}

2.根据权限信息生成路由的json串

根据用户的权限信息和router/index.js中的asyncRouterMap数组匹配,递归生成数组写入index.js中。
关键代码:/src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

export const constantRoutes = [{
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: 'dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: {
        title: '博思考试系统后台',
        icon: 'dashboard'
      }
    }]
  },

  // 404 page must be placed at the end !!!
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({
    y: 0
  }),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

//异步挂载的路由
//动态需要根据权限加载的路由表
export const asyncRouterMap = [
 //基础数据管理路由
  {
    path: '/basedata',
    component: Layout,
    alwaysShow: true,
    name: 'basedate',
    meta: {
      title: '基础数据管理',
      icon: 'example'
    },
    children: [{
        path: 'category',
        component: () => import('@/views/basedata_center/category'),
        name: 'category',
        meta: {
          title: '题目类别管理',
          icon: 'documentation'
        }
      },
      {
        path: 'subjectType',
        component: () => import('@/views/basedata_center/subjectType'),
        name: 'subjectType',
        meta: {
          title: '题型管理',
          icon: 'edit'
        }
      },
      {
        path: 'subject',
        component: () => import('@/views/basedata_center/subject'),
        name: 'subject',
        meta: {
          title: '题目管理',
          icon: 'ic_skill'
        }
      },
      {
        path: 'combExamConfig',
        component: () => import('@/views/basedata_center/combExamConfig'),
        name: 'combExamConfig',
        meta: {
          title: '组卷配置管理',
          icon: 'tree'
        }
      },
    ]
  },
];
export default router

在/src/store/permission.js中添加动态生成路由方法。

import {
  asyncRouterMap,
  constantRoutes
} from '@/router';

function hasPermission(resources, route) {
  if (route.path) {
    let item;
    resources.some(v => {
      if ( route.path == v.url.replace("/", "")) {
        item = v;
        return true;
      }
    })
    return item
  } else {
    return route
  }
}

function getRouter(resources) {
  return asyncRouterMap.filter(v => {
    if (v.children && v.children.length > 0) {
      v.children = v.children.filter(child => {
        let item = hasPermission(resources, child);
        if (item) {
          if (item.openImg && item.closeImg) {
            child.meta.openIcon = item.openImg
            child.meta.closeIcon = item.closeImg
            return child
          }
          return child
        }
        return false;
      })
      if (v.children && v.children.length > 0) {
        return v
      } else {
        return false
      }
    } else {
      return false
    }
    return false;
  })
}

const permission = {
  namespaced: true,
  state: {
    routers: constantRoutes,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRoutes.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({
      commit
    }, data) { //roles是用户所带的权限
      return new Promise(resolve => {
        const resource = data.filter(item => {
          if (item.resourceType == 0) {
            return item;
          }
        })
        const accessedRouters = getRouter(resource)
        console.log(accessedRouters)
        commit('SET_ROUTERS', accessedRouters);
        resolve();
      })
    }
  },
};

export default permission;

3.触发动态路由的生成

在/src/permission.js中添加登录是触发/src/store/permission.js中的action生成动态路由。
关键/src/permission.js

    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.info
      if (JSON.stringify(hasGetUserInfo) != "{}") {
        next()
      } else {
        try {
          // get user info
          const fromPath = GetUrlRelativePath(window.location.href)
          const userInfo = getUserInfo();
          await store.dispatch('user/login', userInfo)
          //实际是请求用户信息后返回,这里是模拟数据,直接从store中取
          const resources = store.getters.resources;
          // 生成可访问的路由表
          store.dispatch('permission/GenerateRoutes', resources).then(() => {
            // 动态添加可访问路由表
            router.addRoutes(store.getters.addRouters);
            router.options.routes = store.getters.routers;
            next({
              path: fromPath
            }); // 跳转到刷新前的路由
          })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetAuth')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }

你可能感兴趣的:(动态路由)