vue路由配置
代码:index.js
import Vue from 'vue';
import Router from 'vue-router';
import {routers} from './router.config';
Vue.use(Router);
//获取原型对象上的push函数,防止跳转重复路由报错
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
// 路由配置
const RouterConfig = {
// mode: 'history',
routes: routers
};
export default new Router(RouterConfig);
路由配置:router.config.js
export const routers = [
{
path: "/", redirect: "/xxx",
},
];
动态配置路由:
function formatComponent(list) {
list = list.map(item => {
if (item.code === 'routerPage') {
item.component = routerPage;
} else {
item.component = loadView(item.path)
}
if (item.children && item.children.length) {
item.children = formatComponent(item.children)
}
return item
})
return list
}
获取component
function loadView(view) {
if (process.env.NODE_ENV === 'development') {
return (resolve) => require([`@/views${view}`], resolve)
} else {
// 使用 import 实现生产环境的路由懒加载
return () => import(`@/views${view}`)
}
}
export路由:
export const getMenuList = (type) => {
return getMenuApi(type).then(response => {
const menu = [
{
path: '/index',
component: index,
name: "首页",
children: [
...formatComponent(response),
]
},
]
return menu
})
}
main.js
import { getMenuList } from "@/utils/menu.js";
getMenuList('initial').then(menu => {
if(!menu.length || !menu[0].children || !menu[0].children.length) {
window.location.href = getUrl() + '/#/account-login'
}
else {
// 将菜单存储到vuex里
store.commit('setMenuList', menu)
menu.forEach(res=>{
router.addRoute(res);
})
}
})