来源
写路由时每新建一个路由都需要import一下或其他方式(如箭头函数import)很是麻烦,有麻烦就有需求,于是以下这篇文章就来了
吹水
要想动态注册路由,那么就需要制定规则,即每个路由有一定的规则,来实现动态注册,我的路由文件是放在views下,其中每个vue文件有一个对应的包名
借助vue官网中基础组件的自动化全局注册
代码中不难看出归功于webpack的require.context使我们可以获取到文件夹下面的文件,关键点在(files(item).default)获取(不知道怎么取名,望大佬分享下)
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home/Home.vue'
import Login from '../views/login/Login.vue'
Vue.use(VueRouter)
//获取文件,自动挂载在router下
const files = require.context(
// 其组件目录的相对路径
'../views',
// 是否查询其子目录
true,
// 匹配基础组件文件名的正则表达式
/\.vue/
)
let items = [{
path: "",
redirect: "/MenuSystem"
}];
files.keys().forEach(item => {
let name = item.split('/')[2].replace('.vue', "");
items.push({
path: `/${name}`,
component: files(item).default
})
})
const routes = [
{
path: '/Login',
component: Login
},
{
path: '/',
component: Home,
children: [...items]
// children: [{
// path: "",
// redirect: "/MenuSystem"
// }, {
// path: "/MenuSystem",
// component: MenuSystem
// }, {
// path: "/RoleSystem",
// component: RoleSystem
// }, {
// path: "/ActionSystem",
// component: ActionSystem
// }, {
// path: "/SystemAuthority",
// component: SystemAuthority
// }, {
// path: "/MenuAuthority",
// component: MenuAuthority
// }, {
// path: "/PostInfo",
// component: PostInfo
// }
// ]
}, {
path: "*",
redirect: "/"
}
]
// 解决菜单跳转相同路径下报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err);
}
const router = new VueRouter({
mode: 'hash',
base: process.env.BASE_URL,
routes
})
export default router