vue.js - 在值更改时获取对象的索引

时间:2017-08-03 08:46:12

标签: vuejs2

我有这些数据:

products:[
{'name':'product1', 'price':'','syntax':'true'},
{'name':'product2', 'price':'','syntax':'true'},
{'name':'product3', 'price':'','syntax':'true'}
]

我需要注意价格变化:

watch:{
        products:{
            handler: function (val, oldVal) {
                console.log(this.products);
            },
            deep: true
            }
        }

哪个工作正常。但是,我想知道哪个product.price在更改时已被更改,因此我可以查看regex并设置product.syntax是真还是假。如何获取index中的products的{​​{1}}?

2 个答案:

答案 0 :(得分:0)

试试这个,

watch: {
    products: {
        handler: function (val, oldVal) {

            var vm = this;
            let changed = val.filter( function( product, index ) {
                return Object.keys(product).some( function( prop ) {
                return product[prop] !== vm.$data.oldVal[index][prop];
            })

            console.log(changed)
        },
        deep: true
    }
}

答案 1 :(得分:0)

这应该有用。

watch: {
    products: {
        handler(newVal, oldVal) {
            let changedIndex;
            newVal.forEach((product, idx) => {
                if (product.price !== oldVal[idx].price) {
                    changedIndex = idx;
                }
            })
            console.log(changedIndex);
        },
        deep: true
    }
}



const app = new Vue({
  el: '#app',
  data: {
    products:[
      {'name':'product1', 'price': '0','syntax':'true'},
      {'name':'product2', 'price': '3','syntax':'true'},
      {'name':'product3', 'price': '10','syntax':'true'}
    ]
  },
  watch: {
    products: {
      handler(newVal, oldVal) {
        newVal.forEach(product => {
          if (parseInt(product.price) > 5) {
            product.syntax = true;
          } else {
            product.syntax = false;
          }
        })
      },
      deep: true
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <span>Syntax changes to true when price > 5</span>
  <table>
    <th>Name</th>
    <th>Price</th>
    <th>Syntax</th>
    <tr v-for="(product, idx) in products">
      <td>{{product.name}}</td>
      <td><input type="text" v-model="product.price"/></td>
      <td>{{product.syntax}}</td>
    </tr>
  </table>
</div>
&#13;
&#13;
&#13;