<template>
<div id="app">
<div v-for="item in shop" :key="item.id" class="box">
<input
type="checkbox"
@change="checkChange(item)"
:checked="item.checked"/>
序号:{{ item.id }}
商品名称:{{ item.name }}
价格:{{ item.price }}
数量:{{ item.number }}
<button @click="add(item)">{{ item.add }}</button>
<button @click="sub(item)">{{ item.reduce }}</button>
</div>
<strong>总和: <span>{{ money }}</span></strong>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
money: 0,
shop: [
{
checkbox: false,
id: 1,
name: "苹果",
price: 12,
number: 1,
add: "新增",
reduce: "减少",
},
{
checkbox: false,
id: 2,
name: "苹果",
price: 12,
number: 2,
add: "新增",
reduce: "减少",
},
{
checkbox: false,
id: 3,
name: "苹果",
price: 12,
number: 3,
add: "新增",
reduce: "减少",
},
{
checkbox: false,
id: 4,
name: "苹果",
price: 12,
number: 4,
add: "新增",
reduce: "减少",
},
],
};
},
//初始化加载 显示总价总数量
// created: function () {
// // `this` 指向 vm 实例
// // console.log(this.shop);
// var sum = 0;
// for (var i = 0; i < this.shop.length; i++) {
// // console.log(this.shop[i]); //打印商品
// // console.log(this.shop[i].price);
// sum = sum + this.shop[i].price * this.shop[i].number;
// }
// this.money = sum;
// },
methods: {
//加
add: function (item) {
item.number++;
var sum = 0;
// for (var i = 0; i < this.shop.length; i++) {
// // console.log(this.shop[i]); //打印商品
// // console.log(this.shop[i].price);
// sum = sum + this.shop[i].price * this.shop[i].number;
// }
//如果复选框被选中 则商品价格*数量
if (item.checked) {
for (var i = 0; i < this.shop.length; i++) {
sum = sum + this.shop[i].price * this.shop[i].number;
}
}
this.money = sum; //赋值给总价
},
//减
sub: function (item) {
item.number--;
var sum = 0;
if (item.checked) {
for (var i = 0; i < this.shop.length; i++) {
sum = sum + this.shop[i].price * this.shop[i].number;
}
}
this.money = sum;
if (item.number < 0) {
item.number = 0;
alert("不能再减了");
}
},
//求和
checkChange(row) {
// console.log(this.shop);
var allMoney = 0;
this.shop.forEach((item) => {
if (row != null && item.id == row.id) {
item.checked = !item.checked;
}
if (item.checked) {
//单个总价 = 数量*价格
item.money = item.number * item.price;
//将选中的单个总价进行求和
allMoney = allMoney + item.money;
console.log(allMoney);
}
});
this.money = allMoney;
},
},
};
</script>
<style>
body {
display: flex;
align-items: center;
justify-content: center;
/* position: absolute;
height: 100%;
width: 100%; */
height: 500vh;
}
#app {
width: 60%;
height: 300px;
/* background: chartreuse; */
display: flex;
/* align-items: center; */
justify-content: center;
flex-direction: column;
}
.box {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 30px;
line-height: 30px;
background-color: pink;
padding: 10px 0 10px 0px;
/* text-align: center; */
}
button {
margin-left: 10px;
}
.boxs {
width: 130px;
/* border:1px solid pink; */
}
</style>