Vue更改数组中的对象并触发反应性 [英] Vue change object in array and trigger reactivity

查看:52
本文介绍了Vue更改数组中的对象并触发反应性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I trigger an update when altering part of an object found by index in an array?

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

The docs show how to alter the value of an array:

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

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

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

But how to alter the value of a property on an object in an array without changing the rest of the object?

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

The following works to update the property, but Vue doesn't react to the change until something else triggers an update.

example1.items[indexOfItem].some_object_property = false

推荐答案

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

As long as you call set() once to set the object (with the property you are going to update) in the array, Vue will react to changes in the object's properties. Here's an example that has one array of objects initialized in our app's data, and another array of objects manually set (with Vue.set()) when mounted. Clicking the button updates a property on one object in each of those arrays, and Vue reacts. Note that the set() call that happens in mount() could really happen anytime.

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();
    }
  }
})

这篇关于Vue更改数组中的对象并触发反应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆