Vue.js 不允许我更改数组值:
<div class="col-sm-1 col-md-1" v-for="(l, i) in locations" :key="i">
<span :class="{'location-active': isActive[1]}" @click="setActive">{{l}}</span>
</div>
数据:
data() {
return {
isActive: [false, false, false, false, false]
}
}
方法:
setActive() {
this.isActive[1] = true;
}
我首先使用了 for 循环,但它不起作用,所以尝试手动设置数组的值,但它不起作用,它只是不会将 isActive[index] 设置为 true。
最佳答案
这是 Vue 的一个常见“陷阱”,以及它如何找到模型更改。
https://vuejs.org/2016/02/06/common-gotchas/
When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property. Similarly, Vue.js cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is syntax sugar for arr.splice(index, 1, value).
语法在 2.0 中更新如下:
Vue.set(目标,属性名称/索引,值)
所以在你的情况下
Vue.set(this.isActive, 1 ,true);
另见此处:http://vuejs.org/guide/list.html#Array-Change-Detection
关于javascript - Vue js 改变数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503926/