computed属性和watch属性的区别之三【购物车之watch】
程序员文章站
2022-03-25 18:45:33
...
<body>
<div id = 'app'>
<div>
<h3>{{title}}</h3>
</div>
<div>
<div>
<table>
<thead>
<tr>
<td>名称</td>
<td>价格(元)</td>
<td>数量(kg)</td>
<td>共计(元)</td>
</tr>
</thead>
<tbody>
<tr v-for = 'item in list '>
<td>{{item.name}}</td>
<td><input type="number" v-model = 'item.price'></td>
<td><input type="number" v-model = 'item.number'></td>
<td>{{item.price * item.number}}</td>
</tr>
<tr>
<td>合计</td>
<td>{{single_price_sum}}</td>
<td>{{single_number_sum}}</td>
<td>{{all_total}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.8/vue.min.js"></script>
<script type="text/javascript">
var _vm = new Vue({
data : {
title : 'computed属性和watch属性的区别之三【购物车之watch】',
single_price_total : 0,
single_price_sum : 0,
single_number_sum : 0,
all_total : 0,
list : [
{id : 1, name : '大白菜', price : 10, number : 1, },
{id : 2, name : '小白菜', price : 20, number : 2,},
{id : 3, name : '中白菜', price : 30, number : 3,}
]
},
watch : {
list : {
handler: function (oldValue, newValue) {
console.log('原值:', oldValue, '新值:', newValue) ;
this.m_auto_calc_total() ;
},
deep: true
}
},
methods : {
m_auto_calc_total : function() {
var _single_price_total = 0 ;
var _single_price_sum = 0 ;
var _single_number_sum = 0 ;
var _all_total = 0 ;
for(var i = 0; i < this.list.length; i++) {
var _item = this.list[i] ;
_single_price_sum += parseFloat(_item.price) ;
_single_number_sum += parseFloat(_item.number) ;
_all_total += _item.price * _item.number ;
}
this.single_price_sum = _single_price_sum ;
this.single_number_sum = _single_number_sum ;
this.all_total = _all_total
}
},
mounted : function() {
this.m_auto_calc_total() ;
}
}).$mount('#app') ;
</script>
</body>