报错:Duplicate keys detected: 'upper0'. This may cause an update error.
检测到重复密钥:“upper0”。这可能会导致更新错误。
错误原因: 有相同父元素的多个子元素的v-for有相同的key值。
<template v-for="(item, index) in upperPoints">
<circle
:key="'upper' + index"
:cx="item.x"
:cy="item.y"
fill="red"
r="5"
/>
<text
:key="'upper' + index"
:x="item.x"
:y="item.y-10"
fill="black"
font-size="12"
>
{{ item.name }}
</text>
</template>
这里我们虽然设置了upper+index (也就是它的索引 0,1,2 )来区分于别的v-for,但是现有的两个key值都是upper0,upper1......也出现重复了。
解决方案:
1、修改一下key值
<template v-for="(item, index) in upperPoints">
<circle
:key="'upperPoint' + index"
:cx="item.x"
:cy="item.y"
fill="red"
r="5"
/>
<text
:key="'upperText' + index"
:x="item.x"
:y="item.y-10"
fill="black"
font-size="12"
>
{{ item.name }}
</text>
</template>
这样我们的key值就是 upperPoint0,upperPoint1,upperText0, upperText1,不相同。
2、将它们放到不同的父元素下
总结:有相同父元素的子元素的key必须保持唯一性,重复的key会造成渲染错误。要保持key的唯一性,一般使用唯一标识 id 来作为key。