基于iview-admin實現(xiàn)動態(tài)路由的示例代碼
iview-admin是一個基于vue和iview組件庫實現(xiàn)的管理后臺前端,本文基于iview-admin最新版本,實現(xiàn)基于權(quán)限的動態(tài)路由加載。
本文代碼可參見:https://github.com/MayBeWrong/iview-admin-dynamic-router
背景:
動態(tài)路由:vue的路由,可通過new Router傳入路由數(shù)組定義實現(xiàn),也可以通過router.addRoutes實現(xiàn)。通過router.addRoutes動態(tài)傳入路由定義的方式,稱之為動態(tài)路由。路由數(shù)據(jù)可以全部保存在后臺數(shù)據(jù)庫中,也可以將路由配置在前端,后端返回給前端路由權(quán)限信息,然后匹配過濾,進行加載。本文就這兩種方式分別進行介紹,并且給出實現(xiàn)參考。
目標:
基于iview-admin最新代碼,實現(xiàn)兩種不同的路由動態(tài)加載方式:
- 路由(導(dǎo)航菜單)數(shù)據(jù)全部存儲在后臺
- 路由數(shù)據(jù)配置在前端,后臺只存儲權(quán)限信息
注意:本文通過Mock模擬后端接口
方式1:路由(導(dǎo)航菜單)數(shù)據(jù)全部存儲在后臺
定義路由數(shù)據(jù)結(jié)構(gòu)體,在文件中:src/mock/data.js
export const routersData = [{
path: '/pet',//訪問路徑
name: 'Pet',//路由的名字,這個與i18n有關(guān),需要唯一
meta: {
title: '寵物',//標題
hideInMenu: false,//是否在左側(cè)導(dǎo)航菜單隱藏
icon: 'logo-freebsd-devil'//圖標
},
component: 'components/main',//組件文件路徑,不需要Import
children: [{//嵌套路由
path: 'cat',
name: 'Cat',
meta: {
title: '貓咪',
hideInMenu: false,
icon: 'ios-cloudy-night'
},
component: 'view/pet/cat/Cat.vue'
}, {
path: 'dog',
name: 'Dog',
meta: {
hideInMenu: false,
title: '狗娃',
icon: 'ios-color-filter'
},
component: 'view/pet/dog/Dog.vue'
}, {
path: 'pig',
name: 'Pig',
meta: {
hideInMenu: false,
title: '豬啊',
icon: 'ios-contact'
},
component: 'view/pet/pig/Pig.vue',
children: [
{
path: 'female',
name: 'Female',
meta: {
hideInMenu: false,
title: '母豬',
icon: 'ios-contact'
},
component: 'view/pet/pig/Pig.vue',
},
{
path: 'male',
name: 'Male',
meta: {
hideInMenu: false,
title: '公豬',
icon: 'ios-contact'
},
component: 'view/pet/pig/Pig.vue',
}
]
}]}]
暴露ajax調(diào)用接口:src/mock/index.js,中增加:
Mock.mock(/\/sys\/routers/, routersData)
實現(xiàn)一個ajax調(diào)用:src/api/routers.js中增加:
export const getRouterReq = (access) => {
return axios.request({
url: '/sys/routers',
params: {
access
},
method: 'get'
})}
1、在store中定義動態(tài)路由相關(guān)邏輯,修改:src/store/module/app.js
引入ajax請求:
import {getRouterReq} from '@/api/routers'
定義兩個state,如下
state: {
.....
routers: [],//拿到的路由數(shù)據(jù)
hasGetRouter: false//是否已經(jīng)拿過路由數(shù)據(jù)
},
同步增加mutations:
mutations:{
......
//設(shè)置路由數(shù)據(jù)
setRouters(state, routers) {
state.routers = routers
},
//設(shè)置是否已經(jīng)拿過路由
setHasGetRouter(state, status) {
state.hasGetRouter = status
}......}
增加一個action:
action:{
........
getRouters({commit}) {
return new Promise((resolve, reject) => {
try {
getRouterReq().then(res => {
let routers = backendMenusToRouters(res.data)
commit('setRouters', routers)
commit('setHasGetRouter', true)
resolve(routers)
}).catch(err => {
reject(err)
})
} catch (error) {
reject(error)
}
})
},
........
}
此處用到了一個函數(shù):backendMenusToRouters,這個函數(shù)定義在src/libs/util.js中,用來對后端返回的路由數(shù)據(jù)遞歸處理,行程vue的路由。
export const backendMenusToRouters = (menus) => {
let routers = []
forEach(menus, (menu) => {
// 將后端數(shù)據(jù)轉(zhuǎn)換成路由數(shù)據(jù)
let route = backendMenuToRoute(menu)
// 如果后端數(shù)據(jù)有下級,則遞歸處理下級
if (menu.children && menu.children.length !== 0) {
route.children = backendMenusToRouters(menu.children)
}
routers.push(route)
})
return routers
}
修改src/router/index.js,增加動態(tài)路由加入邏輯,主要方法:
const initRouters = (store) => {
//這個人登錄了已經(jīng)
if (store.state.user.hasGetInfo) {
//路由加載過了
if (store.state.app.hasGetRouter && store.state.app.routers && store.state.app.routers.length > 0) {
console.log("已經(jīng)加載過了路由")
} else {
//加載路由
console.log("開始加載路由權(quán)限...")
store.dispatch('getUserMenus').then(routers => {
//此處routers已經(jīng)是按照權(quán)限過濾后的路由了,沒權(quán)限的,不加入路由,無法訪問
//路由重置一下把404放最后
const newRouter = new Router({
routes,
mode: config.routerModel
})
router.matcher = newRouter.matcher;
//把404加最后面,如果用router.push({name:'xxxx'})這種的話,404頁面可能空白,用path:'/aa/bb'
router.addRoutes(routers.concat([{
path: '*',
name: 'error_404',
meta: {
hideInMenu: true
},
component: () => import(/* webpackChunkName: "404" */'@/view/error-page/404.vue')
}]))
}).finally(() => {
})
}
}}
每次路由加載之前,都會判斷是否已經(jīng)初始化過系統(tǒng)路由,如果沒有,則初始化。
至此,動態(tài)路由基本實現(xiàn)。文章可能有遺漏和不足,歡迎探討。第二種實現(xiàn)方式
具體實現(xiàn),請參見: https://github.com/MayBeWrong/iview-admin-dynamic-router
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解基于Vue cli開發(fā)修改外部組件Vant默認樣式
這篇文章主要介紹了詳解基于Vue cli開發(fā)修改外部組件Vant默認樣式,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Vue3+TS+Vite+NaiveUI搭建一個項目骨架實現(xiàn)
本文主要介紹了Vue3+TS+Vite+NaiveUI搭建一個項目骨架實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
vue使用websocket實現(xiàn)實時數(shù)據(jù)推送功能
這篇文章主要為大家詳細介紹了vue如何使用websocket實現(xiàn)實時數(shù)據(jù)推送,發(fā)布訂閱重連單點登錄功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12
Vue實現(xiàn)網(wǎng)頁首屏加載動畫及頁面內(nèi)請求數(shù)據(jù)加載loading效果
Loading加載動畫組件看起來很簡單不重要,實際上它是保證用戶留存的關(guān)鍵一環(huán),下面這篇文章主要給大家介紹了關(guān)于Vue實現(xiàn)網(wǎng)頁首屏加載動畫及頁面內(nèi)請求數(shù)據(jù)加載loading效果的相關(guān)資料,需要的朋友可以參考下2023-02-02

