gpt4 book ai didi

javascript - 检查所有复选框vuejs

转载 作者:行者123 更新时间:2023-12-03 02:14:28 24 4
gpt4 key购买 nike

我在表格中显示用户列表,每一行都有一个用于选择用户的复选框,复选框值是用户的 ID。所选 ID 依次显示在表格下方的范围内。

如何在单击表格标题中的“全选”复选框时选择所有复选框并取消选择所有复选框?我是与 DOM 交互来执行此操作还是通过 vue 对象进行交互,我认为应该是后者,但非常不确定如何完成看似简单的任务?!任何帮助将不胜感激!

HTML

<div id="app">
<h4>Users</h4>
<div>
<table>
<tr>
<th>Name</th>
<th>Select <input type="checkbox" @click="selectAll"></th>
</tr>
<tr v-for="user in users">
<td>{{ user.name }}</td>
<td><input type="checkbox" v-model="selected" value="{{ user.id }}"></td>
</tr>
</table>
</div>

<span>Selected Ids: {{ selected| json }}</span>
</div>

Javascript/Vuejs

new Vue({
el: '#app',
data: {
users: [
{ "id": "1", "name": "Shad Jast", "email": "pfeffer.matt@yahoo.com",
{ "id": "2", "name": "Duane Metz", "email": "mohammad.ferry@yahoo.com"},
{ "id": "3", "name": "Myah Kris", "email": "evolkman@hotmail.com"},
{ "id": "4", "name": "Dr. Kamron Wunsch", "email": "lenora95@leannon.com"},
{ "id": "5", "name": "Brendon Rogahn", "email": "verlie.buckridge@yahoo.com"}
],
selected: []
},
methods: {
selectAll: function() {
// ?
}
}
})

最佳答案

我认为 @Jeremy 的答案更简洁,但它需要每个用户对象上的 checked 属性,如果数据来自 API 请求,则这是没有意义的。

这是用于选择/取消选择所有行的有效且更清晰的代码,而无需在用户对象上添加 checked 属性:

new Vue({
el: '#app',
data: {
users: [
{ "id": "1", "name": "Shad Jast", "email": "pfeffer.matt@yahoo.com" },
{ "id": "2", "name": "Duane Metz", "email": "mohammad.ferry@yahoo.com" },
{ "id": "3", "name": "Myah Kris", "email": "evolkman@hotmail.com" },
{ "id": "4", "name": "Dr. Kamron Wunsch", "email": "lenora95@leannon.com" }
],
selected: []
},
computed: {
selectAll: {
get: function () {
return this.users ? this.selected.length == this.users.length : false;
},
set: function (value) {
var selected = [];

if (value) {
this.users.forEach(function (user) {
selected.push(user.id);
});
}

this.selected = selected;
}
}
}
});
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>

<div id="app">
<h4>User</h4>
<div>
<table>
<tr>
<th><input type="checkbox" v-model="selectAll"></th>
<th align="left">Name</th>
</tr>
<tr v-for="user in users">
<td>
<input type="checkbox" v-model="selected" :value="user.id" number>
</td>
<td>{{ user.name }}</td>
</tr>
</table>
</div>
</div>

请注意,行复选框上的 number 属性是必需的,否则您必须将用户 ID selectAll 方法作为字符串推送,例如 selected.push (user.id.toString());

关于javascript - 检查所有复选框vuejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33571382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com