如何实现这个复杂的逻辑,以下是我写的一部分,说说思路,谢谢大神^-^
<template>
<div>
<table>
<tr>
<td><input type="checkbox" v-model="checkAll">全选({{checkedCount}})</td>
<td>产品名称</td>
<td>价格</td>
<td>数量</td>
</tr>
<tr v-for="(item,$index) in lists">
<td><input type="checkbox" :value="item.id" v-model="checked" @click="currClick($index,$event)"></td>
<td>{{item.productName}}</td>
<td>{{item.price}}</td>
<td>{{item.count}}</td>
</tr>
<tr>
总价:{{total}}
</tr>
</table>
</div>
</template>
<script>
export default{
data() {
return {
checked:[],
totalPrice:[],
lists : [
{
productName:'产品1',
price:'24',
count:'3',
id:1
},
{
productName:'产品2',
price:'25',
count:'6',
id:2
},
{
productName:'产品3',
price:'54',
count:'7',
id:3
}
]
}
},
computed: {
checkAll: {
get: function() {
return this.checkedCount == this.lists.length;
},
set: function(value) {
if (value) {
this.checked = this.lists.map(function(item) {
return item.id
})
} else {
this.checked = []
}
}
},
checkedCount: {
get: function() {
return this.checked.length;
}
},
total(){
let sum = 0;
for(let i=0;i<this.totalPrice.length;i++){
sum += this.totalPrice[i];
}
return sum;
}
},
methods:{
currClick(index,event){
let total = this.lists[index].price * this.lists[index].count;
this.totalPrice.push(total);
console.log(this.totalPrice);
}
}
}
</script>
<style>
tr td{
width:200px;
background: #eee;
padding:10px 0;
}
</style>
https://jsfiddle.net/dont27/L...
我把题主代码试着运行了下,貌似点击单项的时候总价一直在加?
于是我改了一下思路:
html:
js:
全选题主做法我学习了。 单项选中那个,我觉得直接在产品列表里定义一个checked属性,那么总价的计算直接通过过滤列表(条件是checked值)来做计算。而全选的选中和取消,直接对列表做过滤重置。这样少用了不少data变量,好像还不用用到单项的点击了~不知题主意下如何