import _ from 'lodash';
|
import { onActivated, onMounted, onUnmounted, unref } from 'vue';
|
import type { MittTypeKey } from '../utils/mitt';
|
import emitter from '../utils/mitt';
|
|
type UpdateOption<T extends MittTypeKey> = {
|
/** @description 监听的更新事件 */
|
event: T;
|
/** @description 更新函数 */
|
updateFun?: (emitCategory?: MittType[T]) => any;
|
/** @description 数据分类,如果当前数据更新不存在复杂的查询条件,可以只使用 category 去判断是否需要更新 */
|
category?: MittType[T];
|
/** @description 根据此函数判断是否禁止更新 */
|
disableUpdate?: (emitCategory?: MittType[T], category?: MittType[T]) => boolean;
|
};
|
|
const getUnrefObj = (obj) => {
|
return _.mapValues(obj, (value) => {
|
return unref(value);
|
});
|
};
|
|
/**
|
* 按 key 排序
|
* @returns
|
*/
|
const sortObjByKeyStr = (obj) => {
|
const unrefObj = getUnrefObj(obj);
|
const keys = Object.keys(unrefObj).sort();
|
const newObj = {};
|
for (const item of keys) {
|
newObj[item] = unrefObj[item];
|
}
|
|
return JSON.stringify(newObj);
|
};
|
|
/**
|
* 跨菜单更新数据
|
* @param option
|
*/
|
export const useUpdateData = <T extends MittTypeKey>(option: UpdateOption<T>) => {
|
const { event, category, updateFun, disableUpdate } = option;
|
|
let needUpdate = false;
|
let params = null;
|
onMounted(() => {
|
emitter.on(event, (emitCategory) => {
|
if (category) {
|
const categoryStr = sortObjByKeyStr(category);
|
const emitCategoryStr = sortObjByKeyStr(emitCategory);
|
if (emitCategoryStr !== categoryStr) {
|
return;
|
}
|
}
|
if (disableUpdate && disableUpdate(emitCategory, category)) return;
|
|
params = emitCategory;
|
needUpdate = true;
|
});
|
});
|
|
onActivated(() => {
|
if (!needUpdate) return;
|
needUpdate = false;
|
updateFun(params);
|
});
|
|
onUnmounted(() => {
|
emitter.off(event);
|
});
|
};
|