wangzhibo
2026-07-16 b57020623cf0c946706573bf102e548c3a544423
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { type Ref, type WatchStopHandle, getCurrentInstance, watch } from "vue";
import { useConfig } from "../../../hooks";
import { uniqueFns } from "../../../utils";
 
export function usePlugins(enable: boolean, { visible }: { visible: Ref<boolean> }) {
    const that: any = getCurrentInstance();
    const { style } = useConfig();
 
    interface Event {
        onOpen: (() => void)[];
        onClose: (() => void)[];
        onSubmit: ((data: obj) => Promise<obj> | obj)[];
        [key: string]: any;
    }
 
    // 事件
    const ev: Event = {
        onOpen: [],
        onClose: [],
        onSubmit: []
    };
 
    // 监听器
    let timer: WatchStopHandle | null = null;
 
    // 插件创建
    function create(plugins: ClForm.Plugin[] = []) {
        if (!enable) {
            return false;
        }
 
        for (const i in ev) {
            ev[i] = [];
        }
 
        // 停止监听
        if (timer) {
            timer();
        }
 
        // 执行
        uniqueFns([...(style.form.plugins || []), ...plugins]).forEach((p) => {
            const d: any = {
                exposed: that.exposed
            };
 
            for (const i in ev) {
                d[i] = (cb: any) => {
                    ev[i].push(cb);
                };
            }
 
            p(d);
        });
 
        timer = watch(
            visible,
            (val) => {
                if (val) {
                    setTimeout(() => {
                        ev.onOpen.forEach((e) => e());
                    }, 10);
                } else {
                    ev.onClose.forEach((e) => e());
                }
            },
            {
                immediate: true
            }
        );
    }
 
    // 表单提交
    async function submit(data: any) {
        let d = data;
 
        for (let i = 0; i < ev.onSubmit.length; i++) {
            const d2 = await ev.onSubmit[i](d);
 
            if (d2) {
                d = d2;
            }
        }
 
        return d;
    }
 
    return {
        create,
        submit
    };
}