<!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">
<link rel="stylesheet" href="bootstrap.min.css">
<title>vue 计算属性</title>
</head>
<body>
<div class="container">
<h3 class="text-center text-muted">购车结算功能</h3>
<table class="table table-bordered table-striped">
<thead>
<tr>
<td>选择</td>
<th>商品名称</th>
<th>商品单价</th>
<th>数量</th>
<td>是否被选中</td>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in productList">
<td><input type="checkbox" @change="change(index)" v-model="item.selected"></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.number}}</td>
<td>{{item.selected}}</td>
<td>{{item.price*item.number}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">总计</td>
<td>{{totalMoney}}元</td>
</tr>
</tfoot>
</table>
</div>
<script src="vue.js"></script>
<script>
new Vue({
el: ".container",
data: {
productList: [{
name: "苹果",
price: 5.5,
number: 3,
selected: false,
}, {
name: "香蕉",
price: 2.5,
number: 12,
selected: false,
}, {
name: "西瓜",
price: 3.0,
number: 15,
selected: false,
}, {
name: "橘子",
price: 1.5,
number: 5,
selected: false,
}]
},
methods: {
change: function(index) {
//如果选中,则相应索引的商品selected属性为 true
//如果未选中,则相应索引的商品selected属性为 false
// alert(index)
// alert(this.productList[index].selected)
}
},
computed: {
totalMoney: function() {
var sum = 0
for (index in this.productList) {
//判断当前商品的selected属性是否true,如果为true则计入总价中,否则省略
if (this.productList[index].selected) {
sum += this.productList[index].price * this.productList[index].number
}
}
return sum
}
}
})
</script>
</body>
</html>
网友评论