Explaining what I need, here's the code snippet:
Everything works smoothly when adding a product to the items
array if it does not already exist (based on id). However, if it does exist, I only want to update the item. The distinction is based on the id of each item in the items
array.
For example: if first, id = 1, qty = 3, and then next, id = 1, qty = 3, I wish to update the quantity 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>