menuFormat.js(格式化路由表)
export const initMenu = (data) => { let list = []; data.forEach(router => { let { path, component, name, meta, // icon, children } = router; if (children && children instanceof Array) { children = initMenu(children); } let item = { path: path, component: resolve => { if (component == 'layout') { require(['../view/layout/layout.vue'], resolve) } else { require(['../view/test/' + component + '.vue'], resolve) } }, name: name, // icon: icon, meta: meta, children: children }; list.push(item); }) return list; }
登录
<script> import { initMenu } from "@/utils/menuFormat.js"; import { mapState } from "vuex"; export default { data () { }, components: {}, computed: { ...mapState(['menus']) }, methods: { getMenu(){ api_GetUserPermissionById({}) .then((res) => { console.log(res) // 清除404路由(避免出现刷新页面404闪现) this.$router.options.routes.splice(this.$router.options.routes.findIndex(item => item.name === 'NOTFOUND'), 1) this.$router.addRoutes(this.$router.options.routes); let {menulist} = res.result let routerFormat = [] // 格式化路由(将接口数据过滤成路由表需要的格式) menulist.forEach(item=>{ routerFormat.push({ path: item.menuurl, name: item.menuurl.replace('/',''), component: item.menuurl.replace('/',''), meta: { title: item.menuname, icon: item.menuimg } }) }) let sideMenu = initMenu(routerFormat) let routerList = this.$router.options.routes routerList.forEach(item => { if(item.name == 'layout'){ item.children = item.children.concat(sideMenu) } }); let notfound = { path: '*', name: 'NOTFOUND', component: resolve => require(['@/view/layout/notFound.vue'], resolve), hidden: true } routerList.push(notfound) this.$router.addRoutes(routerList); this.$store.commit("ADD_ROUTES", sideMenu); let path = menulist[0].menuurl this.$store.commit("ACTIVE_MENU",path); console.log(path,this.$router.options.routes) this.$router.push({ path: path }) }) .catch((error) => { console.log(error); }); }, } } </script>
store.js
//路由列表 ADD_ROUTES: (state, data) => { state.menus = data; console.log(data) localStorage.setItem('menus', JSON.stringify(data)); },
标签:vue,name,item,菜单,let,path,router,children,路由 From: https://www.cnblogs.com/xhrr/p/16624385.html