Vue.js问题:表格数据更新后选中复选框数据未同步
Vue Data Table Checkbox Selection Sync Issue After Data Update
我最近碰到个头疼的Bug:用Vuetify做了个带复选框选择行的表格,勾选复选框时会自动汇总选中行的金额到merchantTotal里。但当通过日期选择器更新表格数据源(volume)之后,右侧的商家总额以及选中复选框对应的对象里的金额,并没有同步更新成表格里的新数据。
我已经找到一个临时解决办法,但总觉得应该有更优雅的基于v-model的实现方式,试了好多次都没成功,想请教下大家有没有更好的方案。
当前的临时解决逻辑
每次获取新数据后,我会重新筛选并赋值选中的对象,再手动触发金额汇总:
this.volume = response.data; // 计算表格总额 this.total = this.volume.reduce(function(p, n) { return p + parseFloat(n.amount); }, 0); // 保留之前选中的商家名称,重新匹配新数据里的对应项 let merchants = this.selected.map(m => m.merchantName); let filterMerchants = this.volume.filter(e => e ? merchants.includes(e.merchantName) : null); this.selected = filterMerchants; // 手动触发金额汇总 this.onCheckboxChange();
相关代码片段
模板部分
<v-data-table v-model="selected" id="transactions-volume-table" :headers="tableHeaders" :items="volume" item-key="merchantName" :loading="loading" :search="searchTable" hide-actions class="elevation-1" > <v-progress-linear slot="progress" color="blue" indeterminate></v-progress-linear> <template v-slot:items="props"> <td><v-checkbox v-model="props.selected" @change="onCheckboxChange" primary hide-details></v-checkbox></td> <td class="text-xs-left">{{ props.item.divisionName }}</td> <td class="text-xs-left">{{ props.item.merchantName }}</td> <td class="text-xs-left">£{{ props.item.amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") }}</td> </template> </v-data-table>
组件数据与方法
data() { return { search: { fromDate: new Date().toISOString().substr(0, 10), toDate: new Date().toISOString().substr(0, 10) }, fromDateModal: false, toDateModal: false, searchTable: '', loading: true, volume: [], total: null, merchantTotal: 0, tableHeaders: [ { text: 'Select', sortable: false }, { text: 'Division', value: 'divisionName', sortable: true }, { text: 'Merchant', value: 'merchantName', sortable: true }, { text: 'Amount (£)', value: 'amount', sortable: true } ], selected: [] } }, methods: { onCheckboxChange() { console.log(this.selected); this.merchantTotal = this.selected.reduce(function(p, n) { return p + parseFloat(n.amount); }, 0); } }
我现在的写法需要手动处理选中项的重新匹配和方法触发,感觉有点繁琐。有没有办法通过优化v-model的使用,让选中状态和金额汇总能自动跟着数据源更新同步呢?
内容的提问来源于stack exchange,提问作者Dally
相关产品推荐
相关产品推荐

