【发布时间】:2021-08-30 21:12:33
【问题描述】:
这是我的网格 (CRUD) 组件的一部分:
<template>
<table class="MyComponent table">
<thead>
<tr>
<th width="30px">
<b-form-checkbox v-model="allChecked" />
</th>
</tr>
</thead>
<tbody>
<tr v-for="(record, index) in records" :key="index">
<td width="30px">
<b-form-checkbox :value="record['id']" v-model="checkedRows" />
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
name: "MyComponent",
components: {
},
props: ['config'],
data() {
return {
records: [{
id: 1
}, {
id: 2
}, {
id: 3
}, {
id: 4
}, {
id: 5
}, {
id: 6
}],
checkedRows: []
}
},
computed: {
allChecked: {
get() {
return this.records.length == this.checkedRows.length
},
set(v) {
if(v) {
this.checkedRows = [];
for(var i in this.records) {
this.checkedRows.push(this.records[i]['id'])
}
}
else {
this.checkedRows = [];
}
}
}
}
};
</script>
如您所见,我想实现一个标准的、广泛使用的功能:用户可以检查多行并对选定的行进行一些操作。问题在于表格顶部的“全选”复选框。当我检查所有时,然后我从下面的一个复选框中删除勾选,它取消选中页面上的所有复选框。
我理解它发生的原因:当我从下面的复选框中删除一个勾号时,“this.records.length == this.checkedRows.length”条件将不再为真,因此“allChecked”计算变量将设置为 false,因此顶部复选框将设置为未选中。问题是:当顶部的复选框被取消选中时,所有的复选框也将被取消选中,因为计算变量的“设置”部分。
Vue 中是否有干净的方法来解决这个问题?
【问题讨论】: