最近公司新开了一个基于iview admin2.0的前端项目。
由于为了和原有的CS客户端和网站的菜单保持一致。所以要求菜单统一从数据库中获取。
目前想到的方法是在开始访问时从通过后台从数据库中读取菜单数据。然后添加到菜单中。还不是很完善,不过暂时目的是达到了。记录一下改的方法。
1.把脚手架中原有的路由中用不到的示例那部分删掉。保留login,home,401,500等。(404比较特殊)
2.在api文件夹中添加router.js。添加读取菜单路由的方法
export const getCustomRouters = () => { return axios.request({ url: '', method: 'get', data: {} }) }
3.在lib/util.js中添加解析菜单数据的的函数。此时再把404页面添加到该已解析完的路由的后面。原因是如果原路由存在404,每次加载刷新时会先进入到404页面。
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函数修改如下
menuList: (state, getters, rootState) =>
getMenuByRouter(state.menuRouters, rootState.doc.access),
errorCount: state => state.errorList.length