大家好!我叫戴向天
QQ群:602504799
如若有不理解的,可加QQ群进行咨询了解
interface IStore {
_actions: any;
getters: any;
}
/**
* 获取模块名称和指定的方法
* @param args
*/
function getArgumentsResult(...args: any[]) {
const arg = args[0];
let module = null;
let methods: string[] = [];
if (arg[0] && typeof arg[0] === 'string') {
module = arg[0];
} else if (arg[0] && Array.isArray(arg[0])) {
methods = arg[0];
}
if (arg[1] && Array.isArray(arg[1]) && methods.length === 0) {
methods = arg[1];
}
return {
module,
methods: methods.filter((item: any) => typeof item === 'string'),
};
}
/**
* 获取指定模块的所有方法
* @param store Vuex
* @param type 字段名称
* @param module 模块名称
*/
function getModuleMethods(
store: IStore,
type: string,
module: string | null = '',
) {
let methods: any = {};
switch (type) {
case '_actions':
case 'getters':
methods = store[type];
break;
}
const isGetter = type === 'getters';
return Object.keys(methods).reduce((first: any, key: string) => {
const originMethod = isGetter ? () => methods[key] : methods[key][0];
if (module) {
if (key.indexOf('/') >= 0) {
const strs = key.split('/');
const currentModule =
strs.length > 2 ? strs.slice(0, strs.length - 1).join('/') : strs[0];
const methodName = strs.length > 2 ? strs[strs.length - 1] : strs[1];
if (currentModule === module) {
first[methodName] = originMethod;
}
} else if (key.indexOf('/') > -1) {
first[key.split('/')[1]] = originMethod;
}
} else if (key.indexOf('/') === -1) {
first[key] = originMethod;
}
return first;
}, {});
}
/**
* 获取模块方法集里面的指定方法
* @param moduleMethodsMap 模块的所有方法
* @param methods 需要保留的方法
*/
function moduleMethodsFilter(moduleMethodsMap: any, methods: string[]) {
return Object.keys(moduleMethodsMap).reduce((first: any, key: string) => {
if (methods.length) {
if (methods.indexOf(key) > -1) {
first[key] = moduleMethodsMap[key];
}
} else {
first[key] = moduleMethodsMap[key];
}
return first;
}, {});
}
const method = {
/** 获取方法 */
getActions() {
return method.get.call(this, '_actions', arguments);
},
/** 获取数据 */
getGetters() {
return method.get.call(this, 'getters', arguments);
},
$commit() {
//
},
/** 封装 */
get(name: string, ...args: any[]) {
const { module, methods } = getArgumentsResult(args[0]);
const moduleMethods = getModuleMethods((this as any).$store, name, module);
return moduleMethodsFilter(moduleMethods, methods);
},
};
export default method;