gpt4 book ai didi

javascript - vue如何去除重复列表?

转载 作者:行者123 更新时间:2023-11-30 20:48:51 27 4
gpt4 key购买 nike

加入购物车的时候,明明是重复的,我觉得不应该!当我点击+,然后遍历添加购物车的列表,这是重复的,我希望这是添加到购物车的列表应该是唯一的!转到 jsfiddle .

看动图:

enter image description here

看图:

enter image description here

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
item.quantity += 1
console.log("add:", this.addcart.push(item))

},
showCarts(){
//this.showcart = true
}
}
})

HTML:

<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>

最佳答案

您可以先搜索该项目是否在列表中,如果不在列表中,则只需添加项目,但如果项目在数组中,则只需增加数量:

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);
}
},

关于javascript - vue如何去除重复列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48404072/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com