<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
table {
width: 800px;
margin: 0 auto;
}
table td {
text-align: center;
}
</style>
</head>
<body>
<!-- <script src="../js/vue.js"></script> -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.common.dev.js"></script>
<div id="app">
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<th><input type="checkbox" v-model="allChecked" />全选 </th>
<th>商品名称</th>
<th>购买数量</th>
<th>商品价格</th>
<th>小计</th>
</tr>
<tr v-for="item in iceCream" :key="item.id">
<td><input type="checkbox" v-model="item.ischeck" /></td>
<td>{{item.name}}</td>
<td>{{item.num}}</td>
<td>{{item.price}}</td>
<td>{{item.num*item.price}}</td>
</tr>
<tr>
<td>总计:</td>
<td colspan="4">{{total}}</td>
</tr>
</table>
</div>
<script>
var vm = new Vue({
el: '#app',
data() {
return {
iceCream: [{
id: 98,
name: '哈根达斯',
num: 10,
price: 98,
ischeck: true
},
{
id: 56,
name: '八喜',
num: 1,
price: 48,
ischeck: false
},
{
id: 102,
name: '冰雪皇后',
num: 1,
price: 29,
ischeck: false
},
{
id: 106,
name: '蒙牛',
num: 10,
price: 4,
ischeck: true
}
]
}
},
computed: {
//总数方法1
total3() {
return this.iceCream.reduce(function (cur, val) {
if (val.ischeck) {
return cur + val.num * val.price;
} else {
return cur;
}
}, 0)
},
//总数方法2
total() {
return this.iceCream.reduce((cur, val) => cur + (val.ischeck ? val.num * val.price : 0), 0)
},
//设置全选和反选
allChecked: {
get() {
//所有的小选框,决定全选框的值
return this.iceCream.every(el => el.ischeck);
},
set(value) {
//console.log(value)
this.iceCream.forEach(el => el.ischeck = value);
}
}
}
})
</script>
</body>
</html>