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

Vue数组添加重复数字引发DOM元素显示异常问题求助

问题描述

向数组添加已存在的数字时,DOM中该数字会重复显示并导致元素异常,但数组本身的状态是正常的。相关代码如下:

监听器(Watcher)

lastWins(){
    console.log(this.lastWins);
    this.lastWins.shift();
}

DOM模板

<ul class="gameHistoryList_rou">
    <li :style="{background: historyCheckColor(win)}" v-for="win of lastWins" :key="win">{{ win }}</li>
</ul>

添加元素的方法

this.lastWins.push(Math.round(Math.random() * 36));
this.lastWins = this.lastWins.splice(0);
问题原因及解决办法

原因

Vue的v-for通过:key识别列表元素的唯一性。你直接用数组元素值win作为key,当数组中出现重复数字时,多个<li>会拥有相同的key。这会导致Vue的虚拟DOM对比算法无法正确追踪元素变化,最终引发DOM渲染异常。

解决办法

  1. 改用唯一key值:

    • 结合元素值和索引生成唯一key,避免重复:
      <li :style="{background: historyCheckColor(win)}" v-for="(win, index) of lastWins" :key="`${win}-${index}`">{{ win }}</li>
      
    • 如果数组是固定长度的队列结构(比如始终保持N个元素),也可以直接用索引作为key:
      <li :style="{background: historyCheckColor(win)}" v-for="(win, index) of lastWins" :key="index">{{ win }}</li>
      
  2. 优化数组更新逻辑:
    去掉监听器,直接在添加元素时控制数组长度,逻辑更直观且避免监听器的潜在问题:

    const newNum = Math.round(Math.random() * 36);
    this.lastWins.push(newNum);
    // 假设需要保持数组最多5个元素,可根据实际需求调整长度
    if (this.lastWins.length > 5) {
        this.lastWins.shift();
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:40:39