<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/vue.js"></script>
<style>
table {
border: 1px solid gray;
border-collapse: collapse;
}
th,
td {
border: 1px solid gray;
padding: 0 10px;
line-height: 40px;
}
</style>
</head>
<body>
<div id="app">
<table>
<tr>
<th>勾选状态</th>
<th>名称</th>
<th>数量</th>
<th>价格</th>
<th>小计</th>
<th>操作</th>
</tr>
<template v-for="(item,index) in arr">
<tr :key="item.id">
<td><input type="checkbox" v-model="item.check"></td>
<td>{{item.name}}</td>
<td style="padding: 5px 10px;">
<button @click="reduce(item)">-</button>
<input type="text" v-model.number.lazy="item.num" @blur="changeNum(item)">
<button @click="add(item)">+</button>
</td>
<td style="padding: 0px 15px;">{{item.price}}</td>
<td>{{item.xNum}}</td>
<td><button @click="delRow(index)">删除</button></td>
</tr>
</template>
<tr>
<td colspan="3">数量:{{tNum}}</td>
<td colspan="3">总价:{{tMoney}}</td>
</tr>
</table>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
arr: [
{ id: 1, name: "手表", num: 1, price: 299 },
{ id: 2, name: "鞋子", num: 2, price: 500 },
{ id: 3, name: "羽绒服", num: 1, price: 200 },
{ id: 4, name: "棉裤", num: 1, price: 100 },
{ id: 5, name: "秋裤", num: 1, price: 50 },
{ id: 6, name: "电风扇", num: 1, price: 180 }
],
tNum: 0,//总数量
tMoney: 0 //总价格
},
created() {
//改造数据源
this.arr = this.arr.map(item => {
// item.xNum = 0;//新增属性
// item.check=false;//新增属性 勾中状态
this.$set(item, 'xNum', 0);
this.$set(item, 'check', false)
return item;
})
console.log(this.arr,'1111111111');
},
methods: {
add(item) {//加
if (item.num > 9) {
alert('没有库存了');
return;
}
item.num++;//修改数量
// item.xNum = item.num * item.price;//计算小计
item.check = true;
// console.log(this.arr);
},
reduce(item) {//减
if (item.num > 1) {
item.num--
item.check = true;
}
// item.xNum = item.num * item.price;//计算小计
},
delRow(idx) {//删除行
this.arr.splice(idx, 1);
},
changeNum(v) {
if (v.num < 1) {
alert('数量不能小于1');
v.num = 1;
}
if (v.num > 10) {
v.num = 10;
alert('超过了库存量');
}
v.check = true;
}
},
watch: {
//监听数据源的改变 深监听
arr: {
deep: true,
handler: function (newV) {
// console.log(1111);
// console.log(newV);
//遍历数组,选中的计算小计、总数量、总价格
let tN = 0, tM = 0;//总数量和总价格
newV.forEach(item => {
if (item.check) {//选中
item.xNum = item.price * item.num;
tN += item.num * 1;//计算总数量
tM += item.xNum * 1;//计算总价格
} else {
item.xNum = 0;//恢复
}
});
this.tNum = tN;
this.tMoney = tM;
}
}
}
})
</script>
</body>
</html>