最近公司新開了一個基於iview admin2.0的前端項目。前端
因爲爲了和原有的CS客戶端和網站的菜單保持一致。因此要求菜單統一從數據庫中獲取。vue
目前想到的方法是在開始訪問時從經過後臺從數據庫中讀取菜單數據。而後添加到菜單中。還不是很完善,不過暫時目的是達到了。記錄一下改的方法。node
1.把腳手架中原有的路由中用不到的示例那部分刪掉。保留login,home,401,500等。(404比較特殊)ios
2.在api文件夾中添加router.js。添加讀取菜單路由的方法數據庫
export const getCustomRouters = () => { return axios.request({ url: '', method: 'get', data: {} }) }
export const getRouters = routes => { let rootRoute = [] AddRouters(routes, rootRoute) rootRoute.push({ path: '*', name: 'error_404', meta: { hideInMenu: true }, component: () => import('@/view/error-page/404.vue') }) return rootRoute } const AddRouters = (routes, rootRoute) => { routes.forEach(element => { let path = '' + element.f_id let title = '' + element.f_title let access = [element.f_function] // judeg node type to generate components let component = {} if (element.f_type == 1) { if (element.parent_id == 0) { path = '/' + path component = Main } else { component = parentView } } else { if ( element.component_reflect != '' && element.component_reflect != undefined ) { component = () => import('@/view/' + element.component_reflect) } } // add node to route tree let thisNode = { path: path, name: title, component: component, meta: { title: title, // hideInBread: false, // hideInMenu:false, // notCache:false, access: access, icon: '_qq' // beforeCloseName:'' }, children: [] // redirect: to => {}, // alias: '', // props: {} } if (element.children != undefined && element.children.length > 0) { AddRouters(element.children, thisNode.children) } rootRoute.push(thisNode) }) }
4.可是發現單純的添加路由,側邊欄並不會響應路由的改變而變化,因此我想到的方法是更改狀態管理。在/store/module/app.js中添加menuRouters狀態,初始值爲引入的路由routers,這樣能保證側邊欄刷新。並將getters中的menuList函數修改以下axios
menuList: (state, getters, rootState) =>
getMenuByRouter(state.menuRouters, rootState.doc.access),
errorCount: state => state.errorList.length
mutations中添加updateRouter函數api
updateRouter (state, route) { // state.menuRouters.append // alert(route) route.forEach(function (value, key, arr) { state.menuRouters.push(value) }) // alert(state.menuRouters) }
5.在main.js的中引入上述函數並在mounted函數中調用app
mounted() { // 調用方法,動態生成路由 getCustomRouters() .then(res => { let secondRouter = res.data.children let addRouters = getRouters(secondRouter) router.addRoutes(addRouters) store.commit('updateRouter', addRouters) }) .catch(err => {}) }
存在的問題:刷新頁面時會回到home頁(原先會回到當前頁),估計須要在對狀態管理和路由跳轉部分進行更改後面研究吧。iview