vue2改变数组对象中的值以后不生效

在Vue2 中,直接通过索引或 push 方法向数组添加对象时, Vue 可能无法监测到变化,(因为vue2的响应式系统基于 Object.defineProperty,无法监听数组索引变化)
  1. 使用 Vue.set(或 this.$set)
this.$set(this.myArray, index, newObject);
  1. 使用 Array.prototype.push
this.myArray.push(newObject);
  1. 使用concat或展开运算符(返回新数组)
this.myArray = this.myArray.concat(newObject);
// 或
this.myArray = [...this.myArray, newObject];
  1. 使用 splice
this.myArray.splice(index, 0, newObject);
为什么不能直接通过索引修改
this.myArray[0] = { id: 1, name: 'New Item' }; // ❌ 不会触发视图更新
最佳实践
  • 优先使用 push 或 $set(性能最优)

  • 需要 插入/替换指定位置 时用 splice 或 $set

  • 避免直接修改数组引用(除非必要)

你可能感兴趣的:(javascript,前端,开发语言)