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

sha*_*rey 16 vue.js reactive vuejs2

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

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

__CODE__ 要么 __CODE__

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

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

__CODE__

ton*_*y19 10

您可以直接编辑子属性,然后使用this.$set()触发更新:

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
  }
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

演示


Jor*_*nes 8

只要您调用 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();
    }
  }
})
Run Code Online (Sandbox Code Playgroud)


ant*_*oni 6

这是另一个演示示例,我认为它很好地说明了数组内对象的反应性。在这里尝试一下: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' })
  }
})
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)