Vue更改数组中的对象并触发反应

时间:2017-10-28 00:22:25

标签: vue.js vuejs2 reactive

如何在更改数组中索引找到的对象的一部分时触发更新?

文档显示了如何更改数组的值:

Vue.set(example1.items, indexOfItem, newValue)

example1.items.splice(indexOfItem, 1, newValue)

但是如何在不改变对象其余部分的情况下改变数组中对象的属性值?

以下内容适用于更新属性,但Vue不会对更改作出反应,直到其他内容触发更新。

example1.items[indexOfItem].some_object_property = false

4 个答案:

答案 0 :(得分:7)

您可以使用this.$set()更新数组元素中的子属性。例如,在前两个数组元素中增加x子属性(如果子属性不存在则创建子属性):

methods: {
  update() {
    this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
    this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
  }
}

new Vue({
  el: '#app',
  data() {
    return {
      arr: [
        {
          foo: {
            x: 100,
            y: 200
          }
        },
        {
          foo: {
            /* x does not exist here initially */
            y: 400
          }
        }
      ]
    };
  },

  methods: {
    update() {
      this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
      this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
    }
  }
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>

<div id="app">
  <button @click="update">Update</button>
  <p>arr[0]: {{ arr[0] }}</p>
  <p>arr[1]: {{ arr[1] }}</p>
</div>

codepen

答案 1 :(得分:3)

只要你调用set()一次来设置数组中的对象(你要更新的属性),Vue就会对对象属性的变化做出反应。这是一个示例,其中有一个对象数组在我们的应用程序数据中初始化,另一个对象数组在安装时手动设置(使用Vue.set())。单击该按钮可更新每个阵列中一个对象的属性,Vue会做出反应。请注意,mount()中发生的set()调用可能随时发生。

https://codepen.io/jordan-kalosal/pen/VrwjoR

new Vue({
  el: "#app",
  data: {
    arr: [
      {
        property: 'OBJ1 Prop'
      },
      {
        property: 'OBJ2 Prop'
      }
    ],
    setLater: false
  },
  mounted() {
    this.$set(this, 'setLater', [
      {
        property: 'setLater OBJ1 Prop'
      },
      {
        property: 'setLater OBJ2 Prop'
      }
    ])
  },
  methods: {
    _updateObjProps() {
      this.arr[0].property = (new Date()).toString();
      this.setLater[0].property = (new Date()).toString();
    }
  }
})

答案 2 :(得分:1)

这里是另一个演示示例,我认为可以很好地说明数组内对象的反应性。在此处进行尝试:https://codepen.io/antoniandre/pen/ZdjwKG

JS

new Vue({
  el: "#app",
  data: {
    array: []
  },

  methods: {
    addTimeProp() {
      this.array.forEach(item => {
        this.$set(item, 'time', null)
      })
    },
    updateTimeProp() {
      this.array.forEach(item => {
        item.time = (new Date()).toString()
      })
    }
  },

  created () {
    this.array.push({ name: 'today' }, { name: 'tomorrow' })
  }
})

HTML:PUG

#app
  h1 Reactivity of objects inside an array
  h2 Content of the array
  pre {{ array }}
  button(@click="array.push({ name: 'another day' })") Add another object
  button(@click="addTimeProp") Add `time` property
  button(@click="updateTimeProp") Update `time` property

答案 3 :(得分:1)

如果您不创建任何新属性,您也可以这样做:

this.myArray.find( el => el.id === '123').someValue = 'someValue'

数组内的对象是完全反应性的。