vue-element-admin后台生成动态路由及菜单
创始人
2025-05-29 00:27:49

目录

vue-element-admin后台生成动态路由及菜单

定位:src/router/index.js

定位:mock/user.js

定位:src/permission.js

定位:src/store/modules/permission.js


vue-element-admin后台生成动态路由及菜单


我使用的是官方国际化分支vue-element-admin-i18n
根据自己需求将路由及菜单修改成动态生成
如果直接使用的基础模板 vue-admin-template 自己再下载一份 vue-element-admin 将没有的文件复制到自己的项目里面

定位:src/router/index.js


constantRoutes:通用页面路由
asyncRoutes:动态路由
将 asyncRoutes =[…] 的值复制到文本中,

并且把里面 component: () => import(‘@/views/dashboard/index’), 内容改为 component: (‘dashboard/index’), 凡是有import的都改一下,

以及 component: Layout 我直接改为component: ‘Layout’


对我为什么不全部保留 而是把 @/views/ 删掉 后面会给出答案 当然也可以自己尝试 记忆犹新
并将其修改为 asyncRoutes=[]

定位:mock/user.js


根据自己需求新增接口 在这里只是为了快速配置 所以直接使用了 url: ‘/vue-element-admin/user/info.*’ 这个接口


原接口内容
 

// get user info{url: '/vue-element-admin/user/info\.*',type: 'get',response: config => {const { token } = config.queryconst info = users[token]return {code: 20000,data: info}}},

修改后接口内容

 // get user info{url: '/vue-element-admin/user/info\.*',type: 'get',response: config => {const { token } = config.queryconst info = users[token]const rdata = [.....]//这里是前面复制到文本中的asyncRoutes值 自行加入// mock errorif (!info) {return {code: 50008,message: 'Login failed, unable to get user details.'}}info.routs = rdata //给info多加一个返回值 我随便命名为routsreturn {code: 20000,data: info}}},

定位:src/permission.js

这里就贴一下原文判断 token 后实现的内容,修改的是 try 里面的内容

原代码

  if (hasToken) {if (to.path === '/login') {// if is logged in, redirect to the home pagenext({ path: '/' })NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939} else {// determine whether the user has obtained his permission roles through getInfoconst hasRoles = store.getters.roles && store.getters.roles.length > 0if (hasRoles) {next()} else {try {// get user info// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']const { roles } = await store.dispatch('user/getInfo')// generate accessible routes map based on rolesconst accessRoutes = await store.dispatch('permission/generateRoutes', roles)// dynamically add accessible routesrouter.addRoutes(accessRoutes)// hack method to ensure that addRoutes is complete// set the replace: true, so the navigation will not leave a history recordnext({ ...to, replace: true })} catch (error) {// remove token and go to login page to re-loginawait store.dispatch('user/resetToken')Message.error(error || 'Has Error')next(`/login?redirect=${to.path}`)NProgress.done()}}}} 

修改后 只贴 try 的内容,主要是将请求 info 后得到的数据 都放入 data 中,然后访问 store.dispatch(‘permission/generateRoutes’, data)
这就是定位到 src/store/modules/permission.js 使用里面的 generateRoutes 方法

try {// get user info// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']const data = await store.dispatch('user/getInfo')// console.log(data)// generate accessible routes map based on rolesconst accessRoutes = await store.dispatch('permission/generateRoutes', data)// dynamically add accessible routesrouter.addRoutes(accessRoutes)// hack method to ensure that addRoutes is complete// set the replace: true, so the navigation will not leave a history recordnext({ ...to, replace: true })}

定位:src/store/modules/permission.js

原代码 generateRoutes 方法

generateRoutes({ commit }, roles) {return new Promise(resolve => {let accessedRoutesif (roles.includes('admin')) {accessedRoutes = asyncRoutes || []} else {accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)}commit('SET_ROUTES', accessedRoutes)resolve(accessedRoutes)})}

修改后

  generateRoutes({ commit }, data) {return new Promise(resolve => {const accessedRoutes = filterAsyncRoutes(data.routs, data.roles)commit('SET_ROUTES', accessedRoutes)resolve(accessedRoutes)})}

然后定位到 filterAsyncRoutes 方法
原代码

export function filterAsyncRoutes(routes, roles) {const res = []routes.forEach(route => {const tmp = { ...route }if (hasPermission(roles, tmp)) {if (tmp.children) {tmp.children = filterAsyncRoutes(tmp.children, roles)}res.push(tmp)}})return res
}

修改后代码 以及我自己新加的代码

export const loadView = (view) => {console.log(view)return (resolve) => require([`@/views/${view}`], resolve)
}
export function filterAsyncRoutes(routes, roles) {const list = []routes.forEach(p => {if (hasPermission(roles, p)) {p.component = () => import('@/layout')if (p.children != null) {p.children = getChildren(p.children)}list.push(p)}})return list
}
function getChildren(data) {const array = []data.forEach(x => {const children = JSON.parse(JSON.stringify(x))children.component = loadView(x.component)if (x.children != null) {children.children = getChildren(x.children)}array.push(children)})return array
}

这段代码可能会有些疑惑,在 filterAsyncRoutes 中 我直接定义 component: () => import(‘@/layout’), 是因为我试过动态生成但是因为 会报找不到模块 根据网上查找的资料显示,因为路径的问题。即根据 component 的路径,匹配不到已编译的组件,因为匹配期间不会再计算代码所在文件路径相对 component 的路径。比如 component 的值分别为@/views/index.vue、…/views/index.vue、./views/index.vue,运行期间这些直接拿去跟已注册组件匹配,并不会再次计算真实路径 来自千年轮回的博客
也就是说 尽管是动态生成 也得定义到页面存在的路径前面 没办法直接生成
例如:json里面component : ‘/layout’ 定义路由 component:()=>import(‘@’+component) 是无法生成的 必须写为 import(‘@/layout’) 才能找到模块 建议动手尝试一下
 

相关内容

热门资讯

英语范文摘抄带题目【优秀6篇... 英语范文摘抄带题目 篇一:The Importance of Learning English英语范...
我的外教老师作文(推荐3篇) 我的外教老师作文 篇一我的外教老师是一个非常有才华和热情的人。他来自美国,有着丰富的教学经验和深厚的...
描写未来的英语作文(最新3篇... 描写未来的英语作文 篇一:A Glimpse into the FutureAs I close m...
关于人物的想象范文英语【优选... Title: Imaginary Character - Article OneIn a world...
奥尔森姐妹英语作文(经典3篇... 奥尔森姐妹英语作文 篇一:Mary-Kate Olsen - A Fashion IconMary-...