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

Vue.js 2中如何向现有数组对象的行追加数据?

在Vue.js 2中给数组对象追加属性的方法

当然可以实现啦!在Vue.js 2里给现有数组的每个对象追加新属性,有几种实用的方式,我给你详细说说:

方法一:遍历数组并通过this.$set添加响应式属性

如果你的数组是组件data里的响应式数据,直接给对象加新属性默认不会触发视图更新,这时候就得用this.$set(或者全局的Vue.set)来确保新属性是响应式的。

假设你的数据存在组件的data中:

data() {
  return {
    electricityData: [
      {total_electricity_generated: 1567.7910000000002},
      {total_electricity_generated: 1468.4869999999999},
      {total_electricity_generated: 498.7319999999999},
      {total_electricity_generated: 461.8369999999999}
    ]
  }
}

你可以写一个方法来批量添加属性:

methods: {
  appendNewProperty() {
    this.electricityData.forEach((item, index) => {
      // 用this.$set给每个对象追加anotherValue,值为索引+1
      this.$set(item, 'anotherValue', index + 1)
    })
  }
}

之后在需要的地方调用this.appendNewProperty()就行,比如在created钩子初始化时调用:

created() {
  this.appendNewProperty()
}

如果不需要响应式(比如只是处理数据,不绑定到视图),可以直接赋值,不用this.$set:

this.electricityData.forEach((item, index) => {
  item.anotherValue = index + 1
})

方法二:用map创建新数组替换原数组

这种方式通过生成新数组来替换原数组,Vue能检测到数组的替换操作,从而触发视图更新。代码更简洁:

methods: {
  appendNewProperty() {
    this.electricityData = this.electricityData.map((item, index) => {
      // 解构原对象属性,同时追加新属性
      return {
        ...item,
        anotherValue: index + 1
      }
    })
  }
}

这个方法会返回一个全新的数组,每个元素都是包含原属性和新属性的对象,替换原数组后,响应式系统会自动更新视图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:25:07