vue.js 实现全选,单选,计算商品总价格,商品件数
1.标签
<div id="main-body" class="box">
<div class="main">
<input type="checkbox" v-model="ischecked" @click="allchecked" />全选
<div class="sum">¥{{sum}}.00</div>
<div class="settlement">
<span @click="settlement">结算({{count}})</span>
</div>
</div>
<ul>
<li v-for="(item,index) in goodslist" :key="item.name">
<div class="radio">
<input
type="checkbox"
:checked="item.checked"
@click="changechecked($event,item.name)"
/>
</div>
<div class="title"> {{item.name}} </div>
<div class="price">¥{{item.price}}</div>
<div class="num-count">
<button ref="sub" @click="subcount(item.name)">-</button>
<span>{{item.count}}</span>
<button ref="add" @click="addcount(item.name)">+</button>
</div>
</li>
</ul>
</div>
2. js部分
2.1 data部分
data: {
sum: 0,
ischecked: false,
count: 0,
goodslist: [
{
name: "亚托克斯",
price: 100,
checked: false,
count: 1,
},
{
name: "安妮",
price: 150,
checked: false,
count: 1,
},
{
name: "阿卡丽",
price: 200,
checked: false,
count: 1,
},
{
name: "阿利斯塔",
price: 150,
checked: false,
count: 1,
},
{
name: "阿木木",
price: 300,
checked: false,
count: 1,
},
],
},
2.2 methods部分
methods: {
//单选按钮
changechecked(e, name) {
let result = this.goodslist.map((item) => {
if (name == item.name) {
item.checked = e.target.checked;
}
return item.checked;
});
let res = result.every((item) => {
return item;
});
if (res) {
this.ischecked = true;
} else {
this.ischecked = false;
}
this.getnewsum();
this.getnumcount();
},
//自减模块
subcount(name) {
//count自减
this.goodslist.filter((item) => {
if (item.name == name) {
if (item.count <= 0) return (item.count = 0);
item.count--;
}
});
this.getnewsum();
this.getnumcount();
},
//自增模块
addcount(name) {
//count自增
this.goodslist.filter((item) => {
if (item.name == name) {
item.count++;
}
});
this.getnewsum();
this.getnumcount();
},
//全选按钮
allchecked(e) {
if (e.target.checked) {
this.goodslist.forEach((item) => {
item.checked = true;
});
} else {
this.goodslist.forEach((item) => {
item.checked = false;
});
}
this.getnewsum(); // 调用计算总价函数
this.getnumcount(); // 调用计算总数函数
},
//结算结果
settlement() {
console.log("你本次消费" + this.sum + ".00");
},
//计算总价格
getnewsum() {
let num = 0;
this.goodslist.find((item) => {
if (item.checked) {
num += item.price * item.count;
}
});
this.sum = num;
},
//计算总数量
getnumcount() {
let count = 0;
this.goodslist.find((item) => {
if (item.checked) {
count += item.count;
}
});
this.count = count;
},
},