我正在根据边界框加载标记.它们来自API,通过Piniastore .我把它们放在我的 map 包装器组件map-view的props 栏中.标记是通过VUE-FOR循环呈现的圆圈标记.

当我在 map 上移动时,props 字段根据状态(itemsList)改变,因此圆圈标记的VUE循环重新加载 map 上的标记和新标记.这个效果真的很好.

but一段时间后,我发现,当我点击一个标记时,另一个标记上会打开一个不同于被点击的标记的弹出标记.有时,整个 map 会因此跳转到一个完全不同的位置.

传单中的标记和弹出窗口的顺序是否存在任何已知问题,从而导致此类问题?有人能想象是什么导致了这种行为吗?我错过了什么吗?

以下是我简化的VUE贴图包装组件:

<template>
 <div id="main-map-wrapper">
  <l-map ref="map" @update:bounds="updateBounds">
    <l-circle-marker v-for="(item, index) in itemsList" :key="index">
      <l-popup>{{item.name}}</l-popup>
    <l-circle-marker>
  </l-map> 
 </div>
</template>  

<script>
import { LCircleMarker, LMap, LPopup } from "@vue-leaflet/vue-leaflet"
import {useItemsStore} from "@/store/itemsStore"; //pinia store

export default defineComponent({
    name: "mapView",
    components: {LCircleMarker, LMap, LPopup},
    props: {
      itemsList: Object
    },
    methods: {
       updateBounds(bounds) {
            useItemsStore.resetToBounds(bounds) //updates the itemsList, which comes from parent
       }
    }
}
</script>

因此,itemsList是react 性的,来自父组件.

我用的是vue3.

推荐答案

问题是您如何指示Vue跟踪列表项.

In more detail, it has to do with :key="index", which tells Vue: "the unique identifier for each marker is its position in the markers array".
Assuming Vue initially renders a list of markers of n elements, when you update the list with different elements, the first n elements from the updated list are not updated/replaced, because Vue looks at their position in the array and, since it didn't change, the DOM elements do not need updating/re-rendering.

Relevant documentation.

要解决这个问题,您必须 for each 标记使用唯一的标识符(位置为id、生成的uuid或类似的位置).一旦您输入实际的唯一标识符后,Vue将能够正确地跟踪列表项(找出哪些DOM元素需要替换,哪些元素更改了数组中的位置).


Why?

By design, Vue requires a key for list rendering, which allows it to optimise the use and re-use of DOM elements when the list is updated. Vue documentation recommends using a primitive value as key (String, Number or Symbol).
When a :key is not specified, Vue uses the index as key, and issues a warning in development mode about the exact problem you're experiencing (potential problems tracking list updates).

当在元素上指定:key="index"时,您将取消该警告,因为您显式地声明为VUE:"I'm OK with using the default behavior (101 as unique identifier), despite its shortcomings (because I'm not going to update this list over the lifecycle of the parent component)".

Vue.js相关问答推荐

如何使用composition api v-model Select 框获取其他JSON 值?

Vue Router中.getRoutes()获取的路由顺序优化建议

:deep() 带有嵌套 scss 规则的语法

将媒体源/流绑定到视频元素 - Vue 3 组合 API

未捕获的类型错误:无法读取未定义的属性initializeApp

如何将 axios/axios 拦截器全局附加到 Nuxt?

VueJS:向左,元素的顶部位置?

Vue.js 从模板中分离样式

如何使用 vue-resource 添加额外的标头来发布请求?

如何像 React 中的 {...props} 一样在 Vue 中解构 props?

重新加载发布到 Github 页面的 Vue 网站时出现 404

我可以使用 vue.js v-if 来判断值是否存在于数组中

Laravel 中的 VueJS 组件实现中的鼠标悬停

中文而不是英文的Element UI分页

Vuetify RTL 风格

组件已注册但未使用 vue/no-unused-components

vue 未在实例上定义,但在渲染期间引用

在 vue js 中的何处以及如何存储 API 端点?

如何访问通用 javascript 模块中的当前路由元字段

这个业务逻辑有多少属于 Vuex?