对象属性更改时如何在vue js中获取对象索引?

时间:2019-02-25 11:32:41

标签: javascript vue.js

我的vue组件代码如下。

data: function () {
    return {   
        products: [ 
            { product_id: '', price: ''}, 
            { product_id: '', price: ''},  
        ],
    }
},

现在,当v-model =“ product_id”更改时,我想获取对象索引。有什么解决办法吗?

<div v-for="(product, key) in products">
    <input type="text" v-model="product.product_id" />
    <input type="text" v-model="product.price" />
</div><!--  /.div -->

谢谢

3 个答案:

答案 0 :(得分:2)

为什么不只添加一些在@change事件上触发的方法?

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: 'Learn JavaScript' },
      { text: 'Learn Vue' },
      { text: 'Play around in JSFiddle' },
      { text: 'Build something awesome' }
    ]
  },
  methods: {
    getIndex(index) {
    	console.log(index)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(todo, index) in todos" @key="index">
    <input type="text" v-model="todo.text" @change="getIndex(index)">
  </div>
</div>

答案 1 :(得分:1)

阅读:findIndex

data() {
    return {
    products: {  
            product: [ 
                { product_id: '1', price: '50'}, 
                { product_id: '2', price: '93'},  
            ],
            another_field: '',
    },
  }
},
watch: {
    'products.product.product_id'(newId) {
    this.products.another_field = this.products.product.findIndex(p => p.product_id == newId)
  }
}

答案 2 :(得分:0)

您可以将手表用于类似这样的事情:

watch: {
   'products.product': {
       handler(newValue, oldValue) {
           // make sure it changed
           if(newValue != oldValue) {
              // get the row that changed
              let [rowChanged] = _.difference(newValue, oldValue);
              // find its index
              let arrayIndex = newValue.indexOf(rowChanged);
           }  
       },
       deep: true
   }
}

类似的事情应该起作用。如果您愿意,可以将所有内容组合到一个jsfiddle中,这样我们就可以看到整个.vue组件。