多层级路由,使用同一个router-view,配合动态菜单使用
- 此模板是动态生成路由时调用
import util from './util';
export default function routeReplaceSelf (component) {
return {
// name 唯一 这里使用了guid
name: `self${util.getGuid()}Component`,
computed: {
showChild () {
const deepestMatchedRoute = this.$route.matched[this.$route.matched.length - 1];
return deepestMatchedRoute.instances.default !== this;
},
},
render (h) {
return this.showChild ? h('router-view') : h(component);
},
};
}
- 结合vuex/store将后台获取的路由菜单信息,配置为路由格式的核心代码
/**
* 得到后端的数据,将其改造成想要的内容 路由格式
* @param children 菜单数组
*/
function diGui (children: any) {
let c: any = [...children];
if (c.length > 0) {
c.map((item: any) => {
item.component = routeReplaceSelf(_import(item.component));
if (item?.children?.length > 0) {
diGui(item.children);
}
});
return c;
}
return c;
}
/**
* 将后端返回的组件路径转换为我们需要的格式
* @/views/PATH/PATH.vue
* @param str 组件路径
*/
function _import (str: any) {
return function (resolve: any) {
require([`@/views/${str}.vue`], resolve);
};
}
- 最后将得到的路由格式数据添加到路由中
let routes: any = {
id: '354564545',
path: '/',
name: 'index',
component: Index,
menuName: '首页',
meta: {
isRouter: true,
},
children: [
...context.state.arrayRouters
]
};
router.addRoute(routes)