Reputation: 490
My vue component code looks like this.
data: function () {
return {
products: [
{ product_id: '', price: ''},
{ product_id: '', price: ''},
],
}
},
Now I want to get object index when v-model="product_id" changed. Is there any solution to get it?
<div v-for="(product, key) in products">
<input type="text" v-model="product.product_id" />
<input type="text" v-model="product.price" />
</div><!-- /.div -->
Thanks
Upvotes: 2
Views: 4151
Reputation: 20844
Why not just add some method that triggers on @change
event?
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>
Upvotes: 5
Reputation: 1941
You can use a watch with something like this:
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
}
}
Something like this should work. If you want you can combine everything into a jsfiddle so we can see the whole .vue component.
Upvotes: 0
Reputation: 499
Read this: 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)
}
}
Upvotes: 1