I modified the data bound by v-for and found that it could not be re-rendered.
After searching, I learned the following methods:
$set is a global method provided by Vue, which is used to add or update properties to responsive objects and trigger view updates. It takes three arguments: the object, the property name or index to add/update, and the new value.
// 参数1:绑定数组/对象,参数2: 索引/key, 参数3: 被修改的值
this.$set(this.clsBut[ind], 1, true);
(Although he said so, but I can directly modify the array and object elements, it can be re-rendered, but v-for cannot re-render the data.)
Case code:
<!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>