@tanshenghu/web-utils
Version:
web公共方法
117 lines (106 loc) • 2.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* 针对UMI框架的router数据优化辅助处理
*/
exports.default = {
/**
* 路由数据美化处理
*/
dealRouter: dealRouter,
/**
* router数据扁平化处理
*/
routerFlat: routerFlat,
/**
* 匹配查找对应路由数据
*/
routerFinder: routerFinder
};
/**
* router flat处理
*/
function routerFlat(router) {
var result = [];
function loop(d) {
d.forEach(function (item) {
if (item.path && item.component) {
result.push(item);
}
var child = item.routes || item.children;
if (Array.isArray(child) && child.length) {
loop(child);
}
});
}
loop(router);
return result;
}
/**
* 匹配动态路由
*/
function routerFinder(pathname, routers) {
if (Array.isArray(routers) && routers.length) {
return routers.find(function (item) {
if (item.path === pathname) {
return true;
} else if (item.path.indexOf('/:') > -1) {
return tileCompare(item.path.replace(/\/:[^\/$]+/g, '').split('/').filter(Boolean), pathname);
}
return false;
});
}
return false;
}
/**
* 路由粒度对比
*/
function tileCompare(tile, pathname) {
pathname += '/';
return tile.every(function (v) {
return pathname.indexOf('/' + v + '/') > -1;
});
}
/**
* 美化UMI的router数据配置
*/
function dealRouter(rs, frs) {
rs.forEach(function (item) {
if (item.url) {
item.path = item.url;
delete item.url;
}
if (Array.isArray(item.routes) && !item.component && item.baseUrl && item.baseUrl.indexOf('/') === 0) {
item.path = item.baseUrl;
delete item.baseUrl;
}
// 对path人性化处理
if (item.path && /^(?:\.\/)|^(?:[a-z])/i.test(item.path)) {
item.path = frs.path + '/' + item.path.replace(/^\.\//, '');
}
if (item.title && !item.name) {
item.name = item.title;
}
if (!item.title && item.name) {
item.title = item.name;
}
if (Array.isArray(item.routes) && item.routes.length) {
// @ts-ignore
[].push.apply(item.routes, [{
path: '/403',
title: '无权限操作',
component: './403',
hideInMenu: true
}, {
component: './404',
title: 'Not Found',
hideInMenu: true
}]);
dealRouter(item.routes, item);
}
});
return rs;
}
module.exports = exports['default'];