<template>
<div class="set">
<h1>使用 $set 给对象新增属性</h1>
<p>{{num}}</p>
<el-button type="primary" @click="increment">+1</el-button>
<p>{{treeData}}</p>
<el-button type="success" @click="addChild">添加子节点</el-button>
</div>
</template>
<script>
export default {
data(){
return{
num:"1",
treeData:[
{id:1,name:'parent1',children:[{id:11,name:'parent11'},{id:12,name:'parent12'},]},
{id:2,name:'parent2'},
{id:3,name:'parent3'},
{id:4,name:'parent4'},
]
}
},
methods:{
increment(){
this.num++
},
addChild(){
const child = {
id:Date.now(),
name:Math.random()
};
// vue3能直接修改数组 proxy
// this.treeData[1].children = [];
// this.treeData[1].children.push(child)21
// console.log(this.treeData,"this.treeData");
// vue不能检测到以下数组的变动 1.利用索引直接设置一个数组项时 2.修改数组长度时 object.definproperty
this.$set(this.treeData[1],'children',[child])
}
},
updated(){
console.log("重新渲染完毕");
}
}
</script>
<style>
.set{
width: 100%;height: 100%;
background: #ccc;
}
</style>