wujingjing
2024-11-19 60197fde6be7b7567bf16524ba1eb227775a6fc8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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);
    });
};