vue 自动生成菜单
阅读原文时间:2023年07月08日阅读:2

import constant from './const'
export function getRouters (files) {
let filenames = files.keys()
let list = mapToList(filenames)
let routerArr = getTree(list)
return routerArr
}

function getTree (list) {
let routers = []
list.map((obj, index) => {
// 当前菜单没有父菜单
if (!hasParent(obj)) {
let length = 0
let routerArr = findChild(obj, obj, list, length)
routers = routers.concat(routerArr)
return routers
}
})
return routers
}

function hasParent (node) {
let arr = node.split('/')
if (arr.length > 1) {
return arr[arr.length - 2]
} else {
return null
}
}

function findChild (node, path, list, length) {
let routerArr = []
let childrenArr = []
let name = node
if (endsWith(node, constant.end)) {
node = cleanAuth(node, constant.end)
}
list.map((obj, index) => {
let arr = obj.split('/')
if (node === arr[length]) {
if (arr.length === length + 2) {
arr.splice(0, length + 1)
let tempNode = arr.toString().replace(',', '/')
childrenArr = childrenArr.concat(findChild(tempNode, obj, list, length + 1))
}
return childrenArr
}
})
routerArr = packageRouter(name, path, routerArr, childrenArr)
return routerArr
}

function packageRouter (name, route, routerArr, childrenArr) {
// path = path.toLocaleLowerCase()
// ../components 不能为第一个变量,否则会报错Cannot find module "."
let path = constant.prefix + '/' + route
if (endsWith(route, constant.end)) {
let tempRoute = cleanAuth(route, constant.end)
if (childrenArr === 'undefined' || childrenArr.length === 0) {
routerArr.push({
path: '/' + tempRoute,
name: tempRoute,
component: resolve => require([`@/${path}.vue`], resolve),
meta: {
requireAuth: true
}
})
} else {
routerArr.push({
path: '/' + tempRoute,
name: tempRoute,
component: resolve => require([`@/${path}.vue`], resolve),
meta: {
requireAuth: true
},
children: childrenArr
})
}
return routerArr
} else {
if (childrenArr === 'undefined' || childrenArr.length === 0) {
routerArr.push({
path: '/' + route,
name: route,
component: resolve => require([`@/${path}.vue`], resolve)
})
} else {
routerArr.push({
path: '/' + route,
name: route,
component: resolve => require([`@/${path}.vue`], resolve),
children: childrenArr
})
}
return routerArr
}
}

function mapToList (filenames) {
let list = []
filenames.map((obj, index) => {
obj = obj.replace(/^\.\//, '').replace(/\.(vue)$/, '')
list.push(obj)
})
return list
}

// 判断当前字符串是否以str开始
// function startsWith (str) {
// return this.slice(0, str.length) === str
// }
// 判断当前字符串是否以str结束
function endsWith (origin, str) {
if (!judgeStrLength) {
return false
}
return origin.slice(origin.length - str.length, origin.length) === str
}

function cleanAuth (origin, str) {
if (!judgeStrLength) {
return origin
}
return origin.slice(0, origin.length - str.length)
}

function judgeStrLength (origin, str) {
return origin.length - str.length > 0
}

export default getRouters

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章