You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Vue3组件作为Leaflet弹窗内容并保留Vue交互能力

此前的Stack Overflow问题演示了如何将Vue2组件作为LeafletJS弹窗的内容,但我无法在Vue3中复现该效果。

提取我代码中的相关片段如下:

<script setup lang="ts">
import { ref } from 'vue'
import L, { type Content } from 'leaflet'
import type { FeatureCollection, Feature } from 'geojson'

import LeafletPopup from '@/components/LeafletPopup.vue'

// 该ref会被Vue匹配到同名的DOM元素
const popupDialogElement = ref(null)

function addFeaturePopup(feature:Feature, layer:L.GeoJSON) {
  if (popupDialogElement?.value !== null) {
    const content:Content = popupDialogElement.value as HTMLElement
    layer.bindPopup(() => content.$el)
  }
}
</script>

<template>
  <div class="map-container">
    <section id="map">
    </section>
    <leaflet-popup ref="popupDialogElement" v-show="false">
    </leaflet-popup>
  </div>
</template>

运行现象:

  • 点击地图时确实会触发弹窗,但弹窗内没有任何内容。
  • 如果将代码第14行修改为:
layer.bindPopup(() => content.$el.innerHTML)

此时弹窗可以正常渲染出预期的HTML标记,但事件绑定、响应式更新等所有Vue特性都会完全失效。

我在JS调试器中查看addFeaturePopup函数时,确认content确实是HTMLElement的实例,无法理解为什么将其传入Leaflet的bindPopup方法无法正常工作。初步推测该问题和Vue3处理ref的机制有关,但暂未找到可行的解决方法。

2022-06-09 更新

应要求提供console.log输出内容:由于内容较长,我已将其上传至代码片段分享平台Gist。


内容的提问来源于stack exchange,提问作者Ian Dickinson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 04:54:25