实现购物车结算功能,效果图如下:
代码如下:
<!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>
<link rel="stylesheet" href="./bootstrap.min.css">
</head>
<body>
<div id="box">
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>全选 <input type="checkbox" name="" id="" v-model="select" @change='selectAll'></th>
<th>商品</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for='(item,index) in cartsList'>
<td><input type="checkbox" v-model="item.isSelected" name="" id="" @change='selOne'></td>
<td>
<img :src="item.productCover" alt="">
<span>{{item.productName}}</span>
</td>
<td>
{{item.productPrice}}
</td>
<td>
<input type="number" name="" id="" v-model="item.productCount">
</td>
<td>
{{(item.productPrice*item.productCount).toFixed(2)}}
</td>
<td>
<button class="btn btn-danger" @click='remove'>删除</button>
</td>
</tr>
<tr>
<td>总计:{{total()}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="./axios.min.js"></script>
<script src="./vue.min.js"></script>
<script>
let vm = new Vue({
el: "#box",
data: {
cartsList: [],
select: false,
},
created() {
axios.get("./carts.json").then(data => {
console.log(data.data);
this.cartsList = data.data;
})
},
methods: {
selectAll() {
console.log(this.cartsList);
this.cartsList.forEach(item => {
console.log(this.select);
item.isSelected = this.select;
})
},
selOne() {
select = this.cartsList.every(function (item) {
return item.isSelected
});
if (!select) {
this.select = false;
} else {
this.select = true;
}
},
remove(index) {
this.cartsList.splice(index, 1);
},
total() {
let num = 0;
this.cartsList.forEach(item => {
if (item.isSelected) {
num += item.productPrice * item.productCount
}
});
return num.toFixed(2);
}
}
})
</script>
</body>
</html>