如何在VueJS中找出被监视数组中的哪个项目被更改?

时间:2017-07-11 19:46:37

标签: javascript vue.js frontend

假设我在数据部分中声明了一个数组

data() {
   return {
      myData : [{foo:2, bar:3},{foo:4,bar:5}]
   }
}

当我更改bar元素的second属性时,我想知道第二个元素已更改。

我的手表功能会是什么样的?

watch : {
  myData : {
     deep : true,
     handler(oldVal, newVal) {
      console.log("New val is the entire myData[] array which is not what I want", newVal);
      // I also want to know what index of the array the changed value belonged to.

     }
  }
}

1 个答案:

答案 0 :(得分:-1)

首先,你的论点是观察者的倒退,因为它应该是newVal, oldVal

此外,我认为此警告可能适用于此: https://vuejs.org/v2/api/#vm-watch

Note: when mutating (rather than replacing) an Object or an Array, the old value will be the same as new value because they reference the same Object/Array. Vue doesn’t keep a copy of the pre-mutate value.