我有一个selectAllToggle函数,它可以被动地选择或取消选择数组中的所有元素。作为回应,当使用selectButton时,浏览器中的所有复选框都显示为选中或取消选中。
当手动选择一个或多个(但不是全部(复选框时,就会出现问题。如果选中任何复选框,则selectButtonName变为";全部取消选择";,当按下时,我希望它取消选择所有。我的代码正确地更新了数组,因为它将数组中每个学生的"selected"属性设置为false,但它的反应性不起作用——手动选择的学生的勾选框在浏览器中保持勾选状态。
selectAllToggle: function(key, row, $event) {
var setTo = false;
var newname = "Select All";
if (this.selectButtonName === "Select All") {
setTo = true;
newname = "Deselect All";
}
if (this.selectButtonName === "Deselect All") {
setTo = false;
newname = "Select All";
}
if (this.students.length > 0) {
for (var i = 0; i < this.students.length; i++) {
this.students[i]['selected'] = setTo;
}
}
this.selectButtonName = newname;
console.log(this.students); //shows the correct 'selected' state for all
},
视图如下(使用vue-tables-2(
<v-client-table
v-if="gridReady"
v-model.sync="students"
:columns="gridcolumns"
:options="gridoptions"
ref="grid">
<input type="checkbox"
slot="selected"
slot-scope="{row, update}"
v-model="row.selected"
@change="selectStudent('select', row, $event)">
</v-client-table>
我该怎么做才能使此函数成为反应函数?
要在选择一个或多个元素后取消选择,可以使用computed property
作为下面的代码段进行反应执行。
new Vue({
el: '#app',
data: {
selected: [],
clientList: [1, 2, 3, 4, 5]
},
computed: {
selectAll: {
get: function() {
return this.selected.length > 0 &&
this.selected.length <= this.clientList.length
},
set: function(value) {
let list = [];
if (value) {
this.selected = this.clientList
} else {
this.selected = []
}
}
}
},
});
<!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">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<div id='app'>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Client Name</th>
<th style="width: 10%"><input type="checkbox" v-model="selectAll" /></th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in clientList">
<td style="font-weight: bold;width: 75%">{{item}}
</td>
<td style="width: 25%">
<input type="checkbox" :value="item" v-model="selected" />
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>