zhangxiao
2024-08-20 e47b788ff5f5c699c682999c95da17eb284ca21d
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
93
94
95
96
<template>
    <div style="display: none">
        <div ref="mapInfoWindowContainer">
            <slot></slot>
        </div>
    </div>
</template>
 
<script lang="ts" setup>
const props = withDefaults(
    defineProps<{
        options: AMap.InfoOptions;
        show: boolean;
    }>(),
    {
        show: false,
        options: () => {
            return {
                content: ""
            };
        }
    }
);
 
const slots = useSlots();
 
const emits = defineEmits<{
    (e: "infoShow"): void;
    (e: "infoClose"): void;
}>();
 
const map = inject<any>("map");
const mapInfoWindowContainer = ref<HTMLElement>();
 
// 单例 InfoWindow 实例
let infoWindow: AMap.InfoWindow | null = null;
 
let observer: null | MutationObserver = null;
 
let slotContent = ref("");
 
function openInfoWindow() {
    if (!map.value) return;
    const options = props.options;
    if (!infoWindow) {
        infoWindow = new AMap.InfoWindow({ ...options, content: slotContent.value });
    } else {
        infoWindow.setContent(slotContent.value);
        infoWindow.setPosition(options.position || map.value.getCenter());
    }
    infoWindow.open(map.value, options.position || map.value.getCenter());
    emits("infoShow");
}
 
function closeInfoWindow() {
    infoWindow?.close();
    emits("infoClose");
}
 
watchEffect(() => {
    if (props.show && slotContent.value) {
        openInfoWindow();
    } else {
        closeInfoWindow();
    }
});
 
const updateSlotContent = () => {
    if (mapInfoWindowContainer.value) {
        slotContent.value = mapInfoWindowContainer.value.innerHTML;
        // 在这里可以使用 slotContent.value 来渲染其他窗体
        // console.log("Slot content updated:", slotContent.value);
    }
};
 
onMounted(() => {
    if (mapInfoWindowContainer.value) {
        observer = new MutationObserver(updateSlotContent);
        observer.observe(mapInfoWindowContainer.value, {
            childList: true,
            subtree: true,
            characterData: true
        });
        // 初始化时也更新一次内容
        updateSlotContent();
    }
});
 
onBeforeUnmount(() => {
    if (observer) {
        observer.disconnect();
    }
});
</script>
 
<style lang="scss" scoped></style>