vue-element-admin后臺(tái)生成動(dòng)態(tài)路由及菜單方法詳解
前言
我使用的是官方國(guó)際化分支vue-element-admin-i18n
根據(jù)自己需求將路由及菜單修改成動(dòng)態(tài)生成
如果直接使用的基礎(chǔ)模板 vue-admin-template 自己再下載一份 vue-element-admin 將沒有的文件復(fù)制到自己的項(xiàng)目里面
定位:src/router/index.js
constantRoutes:通用頁(yè)面路由
asyncRoutes:動(dòng)態(tài)路由
將 asyncRoutes =[…] 的值復(fù)制到文本中,
并且把里面 component: () => import(‘@/views/dashboard/index’), 內(nèi)容改為 component: (‘dashboard/index’), 凡是有import的都改一下,
以及 component: Layout 我直接改為component: ‘Layout’
對(duì)我為什么不全部保留 而是把 @/views/ 刪掉 后面會(huì)給出答案 當(dāng)然也可以自己嘗試 記憶猶新
并將其修改為 asyncRoutes=[]
定位:mock/user.js
根據(jù)自己需求新增接口 在這里只是為了快速配置 所以直接使用了 url: ‘/vue-element-admin/user/info.*’ 這個(gè)接口
原接口內(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 = [.....]//這里是前面復(fù)制到文本中的asyncRoutes值 自行加入
// mock error
if (!info) {
return {
code: 50008,
message: 'Login failed, unable to get user details.'
}
}
info.routs = rdata //給info多加一個(gè)返回值 我隨便命名為routs
return {
code: 20000,
data: info
}
}
},定位:src/permission.js
這里就貼一下原文判斷 token 后實(shí)現(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)容,主要是將請(qǐng)求 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
}這段代碼可能會(huì)有些疑惑,在 filterAsyncRoutes 中 我直接定義 component: () => import(‘@/layout’), 是因?yàn)槲以囘^動(dòng)態(tài)生成但是因?yàn)?會(huì)報(bào)找不到模塊 根據(jù)網(wǎng)上查找的資料顯示,因?yàn)槁窂降膯栴}。即根據(jù) component 的路徑,匹配不到已編譯的組件,因?yàn)槠ヅ淦陂g不會(huì)再計(jì)算代碼所在文件路徑相對(duì) component 的路徑。比如 component 的值分別為@/views/index.vue、…/views/index.vue、./views/index.vue,運(yùn)行期間這些直接拿去跟已注冊(cè)組件匹配,并不會(huì)再次計(jì)算真實(shí)路徑 來自千年輪回的博客
也就是說 盡管是動(dòng)態(tài)生成 也得定義到頁(yè)面存在的路徑前面 沒辦法直接生成
例如:json里面component : ‘/layout’ 定義路由 component:()=>import(‘@’+component) 是無法生成的 必須寫為 import(‘@/layout’) 才能找到模塊 建議動(dòng)手嘗試一下
總結(jié)
到此這篇關(guān)于vue-element-admin后臺(tái)生成動(dòng)態(tài)路由及菜單的文章就介紹到這了,更多相關(guān)vue-element-admin后臺(tái)生成動(dòng)態(tài)路由內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VUEX 數(shù)據(jù)持久化,刷新后重新獲取的例子
今天小編就為大家分享一篇VUEX 數(shù)據(jù)持久化,刷新后重新獲取的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
VUE頁(yè)面中通過雙擊實(shí)現(xiàn)復(fù)制表格中內(nèi)容的示例代碼
這篇文章主要介紹了VUE頁(yè)面中通過雙擊實(shí)現(xiàn)復(fù)制表格中內(nèi)容,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
vue.js實(shí)現(xiàn)選項(xiàng)卡切換
這篇文章主要為大家詳細(xì)介紹了vue.js實(shí)現(xiàn)選項(xiàng)卡切換功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
Vue項(xiàng)目中props傳值時(shí)子組件檢測(cè)不到的問題及解決
這篇文章主要介紹了Vue項(xiàng)目中props傳值時(shí)子組件檢測(cè)不到的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
Vue表格首列相同數(shù)據(jù)合并實(shí)現(xiàn)方法
這篇文章主要介紹了Vue實(shí)現(xiàn)表格首列相同數(shù)據(jù)合并的方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

