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

Vue中添加被监听的变更对象到数组时出现重复添加问题如何解决

问题根因
  • 去重逻辑完全错误:你当前在遍历changedArray的过程中,只要遇到任意一个元素的key1与新变更值的key1不相等,就直接执行插入操作。例如changedArray中已有key1: val1的元素,当key1: val2的变更触发时,遍历到第一个元素就会判定不相等直接插入,后续同key1的变更触发时依然会重复插入,完全没有实现唯一校验的效果。
  • 逻辑顺序颠倒:没有先全局校验目标元素是否已存在,而是在遍历过程中直接触发插入,会导致同一个新值被多次插入到数组中。
修正后的代码
<script>   
export default {
  data() {
    return {
      changedArray: [],
      originalArray: [
         {key1: val1},
         {key1: val2},
         {key1: val3}
      ]
    };
  },
  created() {
    this.originalArray.forEach((val) => {
      this.$watch(() => val, this.handleChange, { deep: true });
    });
  },
  methods: {
    handleChange(newVal) {
      // 先判断数组中是否已存在相同key1的元素
      const isExist = this.changedArray.some(o => o.key1 === newVal.key1)
      // 仅不存在时才插入
      if (!isExist) {
        this.changedArray.push(newVal)
      }
      // 如果需要同步更新已存在元素的最新值,可替换为如下逻辑:
      // const existIndex = this.changedArray.findIndex(o => o.key1 === newVal.key1)
      // if (existIndex === -1) {
      //   this.changedArray.push(newVal)
      // } else {
      //   this.changedArray[existIndex] = newVal
      // }
    },
  }
};
</script>

内容的提问来源于stack exchange,提问作者power-cut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:24:04