我通过类名获取输入元素并添加或删除它们的 "checked "属性来选择所有的复选框。然而,我发现,如果我选中和取消选中任何一个复选框,当我尝试选择所有复选框时,它们不再受到影响。例如,在下图中,我选中和取消选中了前3个复选框。
我所做的事情:1.检查元素--没有看到任何问题,因为尽管页面上没有显示任何变化,但复选框元素的属性仍然在更新.2.控制台--这里没有错误报告。
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="checked"></th>
<th>ID</th>
<th>Course Title</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="course in courses" :key="course.id">
<td><input type="checkbox" class="inputs"></td>
<td>{{course.id}}</td>
<td>{{course.title}}</td>
<td>{{course.price}}</td>
</tr>
</tbody>
</table>
export default {
name: 'CourseTable',
data () {
return {
courses: udemy.results,
checked: false
}
},
methods: {
check (arr) {
for(let i=0; i<arr.length; i++){
arr[i].setAttribute("checked", "")
}
},
uncheck (arr) {
for(let i=0; i<arr.length; i++){
arr[i].removeAttribute("checked")
}
}
},
watch: {
checked: function () {
var inputs = document.getElementsByClassName("inputs")
if(this.checked){
this.check(inputs)
}else{
this.uncheck(inputs)
}
}
}
}
你可以修改这一行 arr[i].setAttribute("checked", "")
到 arr[i].checked = true
和 arr[i].removeAttribute("checked")
到 arr[i].checked = false
其实你可以删除检查和取消检查的方法,也可以删除观察方法。然后改变你的输入检查值。像这样。
new Vue({
el: "#app",
data() {
return {
checked: false,
courses: [{
id: "362328",
title: "AWS",
price: "179.99"
},
{
id: "625204",
title: "The web",
price: "179.99"
}, {
id: "567828",
title: "Complete",
price: "179.99"
}, {
id: "756150",
title: "Angular",
price: "179.99"
}, {
id: "950390",
title: "Machine",
price: "179.99"
}, {
id: "793796",
title: "Excel",
price: "179.99"
}
]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
<table>
<thead>
<tr>
<th><input type="checkbox" v-model="checked"></th>
<th>ID</th>
<th>Course Title</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="course in courses" :key="course.id">
<td><input type="checkbox" class="inputs" :checked='checked'></td>
<td>{{course.id}}</td>
<td>{{course.title}}</td>
<td>{{course.price}}</td>
</tr>
</tbody>
</table>
</div>