web
18 小时以前 49fa0d82a40345342966e810b44429aec0480ef3
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
// @ts-nocheck
import { type ComponentPublicInstance } from 'vue';
// #ifdef APP
function findChildren(selector: string, context: ComponentPublicInstance, needAll: boolean): ComponentPublicInstance [] | null{
    let result:ComponentPublicInstance[] = []
    
    if(context !== null && context.$children.length > 0) {
        const queue:ComponentPublicInstance[] = [...context.$children];
        while(queue.length > 0) {
            const child = queue.shift();
            const name = child?.$options?.name;
            if(name == selector) {
                result.push(child as ComponentPublicInstance)
            } else {
                const children = child?.$children 
                if(children !== null) {
                    queue.push(...children)
                }
            }
            if(result.length > 0 && !needAll) {
                break;
            }
        }
    }
    if(result.length > 0) {
        return result
    }
    return null
}
 
class Query {
    context : ComponentPublicInstance | null = null
    selector : string = ''
    // components : ComponentPublicInstance[] = []
    constructor(selector : string, context : ComponentPublicInstance | null) {
        this.selector = selector
        this.context = context
    }
    in(context : ComponentPublicInstance) : Query {
        return new Query(this.selector, context)
    }
    find(): ComponentPublicInstance | null {
        const selector = this.selector
        if(selector == '') return null
        const component = findChildren(selector, this.context!, false)
        return component != null ? component[0]: null
    }
    findAll():ComponentPublicInstance[] | null {
        const selector = this.selector
        if(selector == '') return null
        return findChildren(selector, this.context!, true)
    }
    closest(): ComponentPublicInstance | null {
        const selector = this.selector
        if(selector == '') return null
        let parent = this.context!.$parent
        let name = parent?.$options?.name;
        while (parent != null && (name == null || selector != name)) {
            parent = parent.$parent
            if (parent != null) {
                name = parent.$options.name
            }
        }
        return parent
    }
}
 
export function selectComponent(selector: string): Query{
    return new Query(selector, null)
}
// #endif
 
// selectComponent('selector').in(this).find()
// selectComponent('selector').in(this).findAll()
// selectComponent('selector').in(this).closest()