我有这些复选框始终保持选中状态,但是我只想检查它们是否与它们所关联的对象的属性包括include设置为true。
现在我的问题是所有复选框都保持选中状态,然后当我单击它们时将其取消选中,然后排除学生。除非选中它们,否则我需要取消选中它们。
我没有在模板上设置选中属性,所以我不知道为什么默认情况下会选中它们?我希望有人能指出我的错误。
我缺席的学生资料:
absentStudents: [{
"id": 207,
"first_name": "Gabriel De Manuel",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Gabriel De Manuel",
"exclude": false ,
"isGrouped": false,
}, {
"id": 208,
"first_name": "Francisco",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Francisco",
"exclude": false,
"isGrouped": false,
}, {
"id": 209,
"first_name": "Rosa",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Rosa",
"exclude": false,
"isGrouped": false,
}],
excludeAbsent: false,
//my v-model is created by the following function
created() {
this.absentStudentsSelected = this.absentStudents.map(x => x.id);
},
我已经为我的列表渲染了这些复选框
<ul>
<li v-for="absentStudent in absentStudents" class="list-unstyled">
<input type="checkbox" @click="check($event)" v-model="absentStudentsSelected" :value="absentStudent.id">
{{ absentStudent.first_name }}
</li>
</ul>
只要this.excludeAbsent为true,请选中每个学生的复选框
check: function(e){
if(this.excludeAbsent === true){ //if we want to include absent students
for(var i = 0; i< this.absentStudents.length; i++){
if(e.target.value == this.absentStudents[i].id){
this.absentStudents[i].include = true
}else{
this.absentStudents[i].include = false
}
}
}
最佳答案
absentStudentsSelected
应该在data选项中初始化为空数组:
let app = new Vue({
el: "#app",
data() {
return {
absentStudents: [{
"id": 207,
"first_name": "Gabriel De Manuel",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Gabriel De Manuel",
"exclude": false,
"isGrouped": false,
}, {
"id": 208,
"first_name": "Francisco",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Francisco",
"exclude": false,
"isGrouped": false,
}, {
"id": 209,
"first_name": "Rosa",
"include": false,
"avatar": null,
"group_id": 24,
"full_name": ", Rosa",
"exclude": false,
"isGrouped": false,
}],
excludeAbsent: false,
absentStudentsSelected: []
}
},
methods: {
check: function(e) {
if (this.excludeAbsent === true) {
for (var i = 0; i < this.absentStudents.length; i++) {
if (e.target.value == this.absentStudents[i].id) {
this.absentStudents[i].include = true
} else {
this.absentStudents[i].include = false
}
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="absentStudent in absentStudents" class="list-unstyled">
<input type="checkbox" @click="check($event)" v-model="absentStudentsSelected" :value="absentStudent.id"> {{ absentStudent.first_name }}
</li>
</ul>
</div>