我修改被v-for绑定的数据,发现居然不能重新渲染。
查找后得知以下方法:
$set 是 Vue 提供的一个全局方法,用于向响应式对象中添加或更新属性,并触发视图更新。它接受三个参数:对象、要添加/更新的属性名或索引,以及新的值。
// 参数1:绑定数组/对象,参数2: 索引/key, 参数3: 被修改的值
this.$set(this.clsBut[ind], 1, true);
(他虽然这样说,但是我直接修改数组和对象元素,是能够重新渲染,但是v-for重新渲染数据不可以。)
案例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue</title>
<style>
.bg {
background-color: rgb(255, 0, 0);
}
</style>
</head>
<body>
<div id="demo">
<input type="button" :value="item[0]" v-for="(item,index) in clsBut" :class="{'bg':item[1]}"
@click="active(item[0])">
{
{clsBut}}
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el: "#demo",
data() {
return {
name: "qhx",
address: "成都",
clsBut: [[1, false], [2, false], [3, false], [4, false]],
};
},
methods: {
active(index) {
let clsButs = this.clsBut
for (const ind in clsButs) {
if (clsButs[ind][0] == index) {
console.log(clsButs[ind][0] == index);
this.$set(this.clsBut[ind], 1, true); // 修改响应性对象
// 达到重新渲染的效果
} else {
this.$set(this.clsBut[ind], 1, false);
}
}
this.clsBut = clsButs
}
},
})
</script>