发现网上有很多方法过滤列表重复项,不过还是要和自己的项目结合之后,才知道是不是想要的。下面只是适合我自己的一种。
<ul>
<li v-for="(item,index) in productsLists" :key="index">
<span>{{item.ID}}</span>
<span>{{item.name}}</span>
<span>{{item.description}}</span>
<span>{{item.price}}</span>
<span><button @click="handleClick(item)">加入购物车</button></span>
</li>
</ul>
<li v-for="(product,index) in cartLists" :key="index">
<span><input type="checkbox" :checked="product.isChecked" :value="index" @click="choose(product)"></span>
<span>{{product.ID}}</span>
<span>{{product.name}}</span>
<span>{{product.description}}</span>
<span>{{product.unitPrice}}</span>
<span><button @click="changeUnit(product,1)">+</button><input class="addRedu" type="number" v-model.number="product.quantity" /><button @click="changeUnit(product,-1)">-</button></span>
<span>{{product.unitPrice*product.quantity}}</span>
<!-- <span>{{subTotal(index) | formatMoney}}</span> -->
<span><button class="del" @click="handleDel(index)">删除</button></span>
</li>
</ul>
vue
data(){
return{
productsLists: [
{
ID: 1002,
name: '百事可乐听装',
description: '可乐型汽水 330ml',
unitPrice: 3.5,
quantity: 1,
total: 0
},
{
ID: 1004,
name: '老干妈',
description: '风味豆豉 280g',
unitPrice: 7.5,
quantity: 1,
total: 0
},
{
ID: 1006,
name: '水杨酸乳膏',
description: '马应龙药业 10g',
unitPrice: 6,
quantity: 1,
total: 0
}
],
sendLists:[]
}
methods: {
//去重
handleClick(item){
//findIndex对于空数组不会执行
let sendItem = this.sendLists.filter(v => v.ID == item.ID)[0];
if(sendItem){
sendItem.quantity ++ ;
}else{
this.sendLists.push({...item, quantity: 1})
}
//this.$store.commit("addList",this.sendLists)
},
//数量变化:只需要写一个方法,通过判断type值
changeUnit(product,type){
if(type>0){
product.quantity ++
}else{
product.quantity --;
if(product.quantity < 1){
product.quantity = 1;
}
};
},
}
加油,前端小白!