JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<ul class="cart-ul">
<li v-for="(item,index) in phone">
Product name: {{item.name}}
<br>Product price:{{item.price}}
<br>
<a class="a-less" @click="lessClick(item)">-</a>
<input type="text" v-model="item.quantity">
<a class="a-add" @click="addClick(item)">+</a>
</li>
</ul>
<!--<button @click="showCarts">
{{addcart.length}}
</button>-->
<div class="cart">
<div>
<ul>
<li v-for="item in addcart">
<p><strong>{{ item.quantity }}</strong> - {{ item.name }}</p>
</li>
</ul>
<h5>Total: <span>{{ total }}</span></h5>
</div>
</div>
</div>
CSS
body {
margin: 0 auto;
}
ul.cart-ul>li {
padding: 0.2rem;
list-style-type: none;
border-bottom: 1px dashed black;
}
.a-less,
.a-add {
height: 2rem;
line-height: 2rem;
padding: 0.1rem;
margin: 0.1rem;
border: 1px solid red;
}
.a-less:hover,
.a-add:hover {
background-color: #0470fd;
color: #fff;
}
JavaScript
const phone = [{
id: "1",
name: "Iphone 4S",
price: 300,
quantity: 0
}, {
id: "2",
name: "Xiaomi",
price: 200,
quantity: 0
}, {
id: "3",
name: "vivo X20",
price: 320,
quantity: 0
}]
var app = new Vue({
el: "#app",
data: {
phone:phone,
addcart: [],
showcart: false,
},
computed: {
total() {
var total = 0;
for (var i = 0; i < this.addcart.length; i++) {
total += this.addcart[i].price;
}
return total;
}
},
methods: {
lessClick(item) {
if (item.quantity > 0) {
item.quantity -= 1
const index = this.addcart.indexOf(item)
if (index > -1) {
const removedName = this.addcart.splice(index, 1)
console.log("remove:", removedName)
}
}
},
addClick(item) {
this.showcart = false
const indexItem = this.addcart.findIndex(x=>x.id === item.id);
if(indexItem >= 0){
this.addcart[indexItem].quantity += 1;
}else{
item.quantity += 1;
this.addcart.push(item);
}
},
showCarts(){
//this.showcart = true
}
}
})