循环渲染无法输出对应ID的Coordinates、Dispatcher等正确结果
解决多目标信息无法正确渲染的问题
问题根源
你当前的代码在循环时不断覆盖单个变量的取值,最后只会保留最后一次循环的结果,同时HTML模板只写了一组展示元素,没有为每个目标生成对应的区块,所以无法显示所有ID的对应数据。
修改步骤
1. 调整数据存储结构
把原来的单个变量改成数组,用来存所有目标的完整信息:
export default { data() { return { targetList: [], // 用数组存储每个目标的信息 } }, }
2. 重构数据处理逻辑
遍历所有features,把每个目标的信息整理后存入数组,不再覆盖单个变量:
// 先清空数组,避免重复数据 this.targetList = []; const features = e.source.data.features; features.forEach(feature => { // 处理坐标格式 const formattedCoords = feature.geometry.coordinates.toString() .replace("[", "") .replace("]", " ") .replace(",", ", "); // 将当前目标的信息存入数组 this.targetList.push({ id: feature.id, coordinates: formattedCoords, dispatcher: feature.properties.name, capturedAt: feature.properties.capturedAt }); });
3. 修改HTML模板,循环渲染每个目标
用Vue的v-for指令循环生成每个目标的信息区块,绑定唯一ID作为key:
<div v-if="zoomLevel > 10" class="search-data" v-for="target in targetList" :key="target.id"> <div><strong>目标ID:</strong> {{ target.id }}</div> <div><strong>Dispatcher:</strong> <span>{{ target.dispatcher}}</span></div> <div><strong>Lng/Lat:</strong> <span>{{ target.coordinates }}</span></div> <div><strong>Captured At:</strong> <span>{{ target.capturedAt }}</span></div> <hr> <!-- 可选,添加分隔线区分不同目标 --> </div>
注意点
- 不要在循环中使用重复的HTML ID(原代码里的
dispatcher、coordinates等ID会重复,不符合规范,所以改成动态绑定或者直接去掉固定ID) :key必须绑定唯一值(这里用目标ID),保证Vue列表渲染的正确性和性能
内容的提问来源于stack exchange,提问作者HelpTheNoob
相关产品推荐
相关产品推荐

