The title describes what I want, this is the code
All is fine when we add a product to items if it doesn't exists (difference by id). But if it exists, I want to modify only the item. The difference is made by id of each item in items array.
Eg : if first, id = 1, qty = 3, and next, id = 1, qty = 3, I want the update of qty in items
new Vue({
el: '#fact',
data: {
input: {
id: null,
qty: 1
},
items: []
},
methods: {
addItem() {
var item = {
id: this.input.id,
qty: this.input.qty
};
if(index = this.itemExists(item) !== false)
{
this.items.slice(index, 1, item);
return null;
}
this.items.push(item)
},
itemExists($input){
for (var i = 0, c = this.items.length; i < c; i++) {
if (this.items[i].id == $input.id) {
return i;
}
}
return false;
}
}
})
<Doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Add product</title>
</head>
<body>
<div id="fact">
<p>
<input type="text" v-model="input.id" placeholder="id of product" />
</p>
<p>
<input type="text" v-model="input.qty" placeholder="quantity of product" />
</p>
<button @click="addItem">Add</button>
<ul v-if="items.length > 0">
<li v-for="item in items">{{ item.qty + ' ' + item.id }}</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
</body>
</html>
You might have misused the slice method, change slice to splice works for me:
this.items.splice(index, 1, item)
slice doesn't trigger view updates according to the documentation here.
Vue wraps an observed array’s mutation methods so they will also trigger view updates. The wrapped methods are:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With