gpt4 book ai didi

vue.js - 单击复选框后 V 模型不会更新

转载 作者:搜寻专家 更新时间:2023-10-30 22:14:13 25 4
gpt4 key购买 nike

知道如何解决这个问题:

在此example ,作者使用 vue 2.3.2 完美运行,

new Vue({
el: '#app',
data: {
users: [{
"id": "Shad",
"name": "Shad"
},
{
"id": "Duane",
"name": "Duane"
},
{
"id": "Myah",
"name": "Myah"
},
{
"id": "Kamron",
"name": "Kamron"
},
{
"id": "Brendon",
"name": "Brendon"
}
],
selected: [],
allSelected: false,
userIds: []
},
methods: {
selectAll: function() {
this.userIds = [];

if (this.allSelected) {
for (user in this.users) {
this.userIds.push(this.users[user].id.toString());
}
}
},
select: function() {
this.allSelected = false;
}
}
})
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>

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

<span>Selected Ids: {{ userIds }}</span>
</div>

当我将其切换到 2.5.16 ( <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> ) 时,行为很奇怪:

当单击 selectAll 复选框时,只有该复选框被选中,但是当我将其切换为取消选中时,下面的所有复选框都被选中

enter image description here

enter image description here

enter image description here

最佳答案

为了一致的浏览器功能,我建议不使用点击/更改复选框。相反,将复选框绑定(bind)到一个值(您已经完成),然后对该值使用观察器。这样,复选框的实际值将始终准确地表示它的状态。所以你会有这样的东西:

<input type="checkbox" v-model="allSelected">


Vue.component({..., {
data: function() {
return {
allSelected: false,
}
}
},
watch: {
allSelected: function(val){
//Use your source of truth to trigger events!
this.doThingWithRealValue(val);
}
}
});

您已经在使用 allSelected 的组件数据值作为真实来源,因此您应该使用这个真实来源作为真正的触发元素值,而不是点击。每当 allSelected 的值发生变化时,您的代码就会运行。这解决了没有渲染顺序怪异的问题。

关于vue.js - 单击复选框后 V 模型不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51430066/

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