我很难从我的应用程序中取出一大块代码来演示这个问题,所以我希望仅仅我的描述就足够清晰,可以引出一些有用的反馈。
我有一个产品表,从 AJAX 调用返回的数组填充。作为调用的一部分,我向数组中的每个对象添加另一个属性:
_.each(this.productList, (product, index) => {
product.selected = true;
});
在我的表格 HTML 中,我有这个:
<tr v-for="(product, index) in this.productList" :data-code="product.code">
<td class='selected'>
<input type="checkbox" :name="'selected'+index" v-model="product.selected">
</td>
etc.
因此,复选框使用"product.selected"作为模型,并且对于数组中的每个项目都已将其设置为 true,因此最初选中了每行的复选框。我可以单击复选框,它会相应地更新底层的"product.selected"属性。到目前为止一切都很好。
我的问题是使用"切换选择"功能,通过单击按钮触发,旨在选中或取消选中所有复选框:
toggleSelection(){
this.allSelected = !this.allSelected; //initially set to true in data object
_.each(this.productList, (product, index) => {
product.selected = this.allSelected;
});
},
这似乎与最初的 AJAX 调用或多或少相同,即遍历 productList 数组并设置数组中每个产品对象的"selected"属性。我可以通过使用 Chrome 中的 Vue 开发工具看到它正在这样做,将"product.selected"设置为真或假。但是,问题是它不会更新用户界面 - 即使每个绑定到的属性已从 true 更改为 false,复选框仍保持选中状态。
这对我来说没有任何意义。为什么在更改绑定对象时未取消选中复选框?
我知道为时已晚,但它可能会帮助某人 我在文档中查看了相同的问题,但没有找到任何东西
玩弄代码,我发现当绑定到添加到原始对象的新属性">在您的情况下,所选属性"时更新 DOM 时出现问题
我的解决方案是将数据加载到新数组中,然后将新属性添加到同一数组中,然后将新数组复制到您的数组"在您的例子中在数据对象中声明 this.productList">
var arr = []
this.loaddata(arr); //this for example loads data from ajax call ,axios or whatever
_.each(arr, (product, index) => {
product.selected = true;
};
this.productList = arr.slice(); //copy the array
我不知道这是否是 Vue 中的问题
将product.selected = true;
替换为Vue.set(product,selected,true);
如果selected
没有设置为 init,它将是伪造的,但它不会是反应性的。
还Vue.set(product, selected, this.allSelected)
.