vue-element-admin后臺生成動態(tài)路由及菜單方法詳解
前言
我使用的是官方國際化分支vue-element-admin-i18n
根據(jù)自己需求將路由及菜單修改成動態(tài)生成
如果直接使用的基礎(chǔ)模板 vue-admin-template 自己再下載一份 vue-element-admin 將沒有的文件復制到自己的項目里面
定位:src/router/index.js
constantRoutes:通用頁面路由
asyncRoutes:動態(tài)路由
將 asyncRoutes =[…] 的值復制到文本中,
并且把里面 component: () => import(‘@/views/dashboard/index’), 內(nèi)容改為 component: (‘dashboard/index’), 凡是有import的都改一下,
以及 component: Layout 我直接改為component: ‘Layout’
對我為什么不全部保留 而是把 @/views/ 刪掉 后面會給出答案 當然也可以自己嘗試 記憶猶新
并將其修改為 asyncRoutes=[]
定位:mock/user.js
根據(jù)自己需求新增接口 在這里只是為了快速配置 所以直接使用了 url: ‘/vue-element-admin/user/info.*’ 這個接口
原接口內(nèi)容
// get user info { url: '/vue-element-admin/user/info\.*', type: 'get', response: config => { const { token } = config.query const info = users[token] return { code: 20000, data: info } } },
修改后接口內(nèi)容
// get user info { url: '/vue-element-admin/user/info\.*', type: 'get', response: config => { const { token } = config.query const info = users[token] const rdata = [.....]//這里是前面復制到文本中的asyncRoutes值 自行加入 // mock error if (!info) { return { code: 50008, message: 'Login failed, unable to get user details.' } } info.routs = rdata //給info多加一個返回值 我隨便命名為routs return { code: 20000, data: info } } },
定位:src/permission.js
這里就貼一下原文判斷 token 后實現(xiàn)的內(nèi)容,修改的是 try 里面的內(nèi)容
原代碼
if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939 } else { // determine whether the user has obtained his permission roles through getInfo const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (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 roles const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // dynamically add accessible routes router.addRoutes(accessRoutes) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } } }
修改后 只貼 try 的內(nèi)容,主要是將請求 info 后得到的數(shù)據(jù) 都放入 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 roles const accessRoutes = await store.dispatch('permission/generateRoutes', data) // dynamically add accessible routes router.addRoutes(accessRoutes) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) }
定位:src/store/modules/permission.js
原代碼 generateRoutes 方法
generateRoutes({ commit }, roles) { return new Promise(resolve => { let accessedRoutes if (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’), 是因為我試過動態(tài)生成但是因為 會報找不到模塊 根據(jù)網(wǎng)上查找的資料顯示,因為路徑的問題。即根據(jù) component 的路徑,匹配不到已編譯的組件,因為匹配期間不會再計算代碼所在文件路徑相對 component 的路徑。比如 component 的值分別為@/views/index.vue、…/views/index.vue、./views/index.vue,運行期間這些直接拿去跟已注冊組件匹配,并不會再次計算真實路徑 來自千年輪回的博客
也就是說 盡管是動態(tài)生成 也得定義到頁面存在的路徑前面 沒辦法直接生成
例如:json里面component : ‘/layout’ 定義路由 component:()=>import(‘@’+component) 是無法生成的 必須寫為 import(‘@/layout’) 才能找到模塊 建議動手嘗試一下
總結(jié)
到此這篇關(guān)于vue-element-admin后臺生成動態(tài)路由及菜單的文章就介紹到這了,更多相關(guān)vue-element-admin后臺生成動態(tài)路由內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vuejs+element UI點擊編輯表格某一行時獲取內(nèi)容填入表單的示例
這篇文章主要介紹了vuejs+element UI點擊編輯表格某一行時獲取內(nèi)容填入表單的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10Vue3+TypeScript+printjs實現(xiàn)標簽批量打印功能的完整過程
最近在做vue項目時使用到了print-js打印,這里給大家分享下,這篇文章主要給大家介紹了關(guān)于Vue3+TypeScript+printjs實現(xiàn)標簽批量打印功能的完整過程,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-09-09Vue源碼之關(guān)于vm.$delete()/Vue.use()內(nèi)部原理詳解
這篇文章主要介紹了Vue源碼之關(guān)于vm.$delete()/Vue.use()內(nèi)部原理詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05詳解Vue 中 extend 、component 、mixins 、extends 的區(qū)別
這篇文章主要介紹了Vue 中 extend 、component 、mixins 、extends 的區(qū)別,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-12-12Vue.js:使用Vue-Router 2實現(xiàn)路由功能介紹
本篇文章主要介紹了Vue.js:使用Vue-Router 2實現(xiàn)路由功能介紹,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02