自动根据文件目录生成vue路由
作者:互联网
前言
每创建一个新的页面需要手动添加路由虽然不是很麻烦的动作,但是也是很繁琐的动作,如果能够再创建文件的时候自动生成路由还是能省一些动作避免一些错误,比如导入路径不对、文件名写错等也不失为一种好的方法。
不意外的导入依赖
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
配置添加路由规则
const filterOptions = {
include: [],
exclude: ['test']
}
关键代码
需要添加路由的文件必须放在“children”文件夹里面
function genRouters ({ include, exclude }) {
const contexts = require.context(
'../views/',
true,
/\.\/(((?!\/).)*|(.*)?children\/(.*)?)\/index\.vue$/,
'lazy'
)
const routers = []
const pathArray = contexts
.keys()
.map(dir => {
const arr = dir
.slice(dir.indexOf('/') + 1, dir.lastIndexOf('/'))
.split('/')
return filterRouters(arr[0]) ? arr : []
})
.sort((a, b) => a.length - b.length)
function filterRouters (router) {
if (!include.length && exclude.length) {
return exclude.indexOf(router) === -1
}
if (include.length && !exclude.length) return include.indexOf(router) > -1
if (include.length && exclude.length) {
return exclude.indexOf(router) === -1 && include.indexOf(router) > -1
}
}
function path2Routers (arr, result = [], i = 0) {
let el = arr[i++]
if (!el) return
if (el === 'children') {
el = arr[i++]
}
const filterItem = result.filter(item => item.name === el)[0]
if (filterItem) {
path2Routers(arr, filterItem.children, i)
} else {
const path = arr.slice(0, i).join('/')
const obj = {
name: el,
children: [],
path: '/' + path.replace(/\/children/g, ''),
component: () =>
import(/* webpackChunkName: "index-[request]" */
/* webpackInclude: /children(\/|\\).*(\/|\\)index\.vue$/ */
`../views/${path}`)
}
result.push(obj)
path2Routers(arr, obj.children, i)
}
return result
}
pathArray.forEach(item => {
if (!item.length) return
const name = item[0]
if (item.length === 1) {
routers.push({
name,
children: [],
path: `/${name}`,
component: () =>
import(/* webpackChunkName: "index-[request]" */
/* webpackInclude: /views(\/|\\)((?!(\/|\\)).)*(\/|\\)index\.vue$/ */
`../views/${name}`)
})
} else {
path2Routers(item, routers)
}
})
return routers
}
创建路由实例
const router = new Router({
routes: [{
path: '/',
redirect: '/login'
},
...genRouters(filterOptions)
]
})
导航守卫
router.beforeEach((to, from, next) => {
// do something...
NProgress.start()
next()
})
router.afterEach((to, from) => {
// do something...
NProgress.done()
})
export default router
标签:arr,vue,const,return,length,router,文件目录,children,路由 来源: https://www.cnblogs.com/wq2022/p/16599774.html