【问题标题】:How do I find out which item in a watched array is changed in VueJS?如何在 VueJS 中找出监视数组中的哪个项目发生了变化?
【发布时间】:2017-07-11 19:46:36
【问题描述】:

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

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

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

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

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.

     }
  }
}

【问题讨论】:

    标签: javascript vue.js frontend


    【解决方案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.
    

    【讨论】:

    • 不过,我如何获取正在变异的数组对象的索引?
    • 我认为这可能首先取决于你如何改变数组
    猜你喜欢
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多