我有一系列文本字段,每个字段旁边都有一个按钮。当用户点击其中一个字段旁边的按钮时,我想向该按钮应用一种特定的样式(以更改其颜色)——本质上允许用户“勾选”他们已检查该字段(类似于 list )。
页面上有九个文本字段/按钮,我将所有按钮的状态存储在名为 items_checked
的数组中,该数组在 data()
中初始化如下:
items_checked: [false, false, false, false, false, false, false, false, false]
每个按钮都有以下代码:
<button class="btn btn-danger" v-on:click="toggleChecked(0)" v-bind:class="{'itemChecked' : items_checked[0]}">
其中数字表示按钮的索引(即 0 是第一个按钮,1 是第二个按钮等),以对应于 items_checked
中的等效 bool 值。
v-on:click
事件只是切换 items_checked
中点击按钮的选中状态:
toggleChecked (itemIndex) {
if (this.items_checked[itemIndex] === false) {
this.items_checked[itemIndex] = true
} else {
this.items_checked[itemIndex] = false
}
console.log(this.items_checked)
}
这可以在 console.log
显示 bool 值切换时发挥作用。
但是,v-bind
不起作用,因为 itemChecked
类未应用于按钮。这似乎是绑定(bind)到数组中 bool 值的问题,因为当我仅绑定(bind)到 data()
中声明的标准 bool 值时,它工作得很好。
我最终需要将所有已检查的状态存储在一个数组中,以便我可以在允许用户提交页面之前评估所有已检查的状态。
如有任何帮助,我们将不胜感激。
最佳答案
这很常见reactivity problem .
在文档中:
Due to limitations in JavaScript, Vue cannot detect the following changes to an array:
When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue
When you modify the length of the array, e.g.
vm.items.length = newLength
您可以使用深层复制
toggleChecked (itemIndex) {
this.items_checked[itemIndex] = !this.items_checked[itemIndex]
this.items_checked = JSON.parse(JSON.stringify(this.items_checked))
console.log(this.items_checked)
}
另一种解决方案是使用Vue.set
toggleChecked (itemIndex) {
var oldValue = this.items_checked[itemIndex]
this.$set(this.items_checked, itemIndex, !oldValue)
console.log(this.items_checked)
}
关于javascript - 基于 bool 值数组在 Vue.js 中绑定(bind)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240588/