基于vue2.x
结论
Vue.set:
作用:修改对象或者数组中的属性或者元素。
当watch检测的是对象或者数组时,set与watch的触发规律。
- 修改已经存在‘儿子’级的属性,不会触发watch事件。
- 修改‘孙子’级的属性,不会触发watch事件。
- 新增‘儿子’级的属性,触发watch事件。
- 新增‘孙子’级的属性,不会触发watch事件。
- 更新’孙子‘级的属性,不会触发watch事件。
Vue.delete:
作用:删除对象或者数组的属性或者元素。
当watch检测的是对象或者数组时,delete与watch的触发规律。
- 删除’儿子’级属性,触发watch事件。
- 删除’孙子’级属性,不会触发watch事件。
代码及运行结果
<template>
<div class="home">
<div>
<button @click="updateGroundSonProperty">修改现有孙子属性</button>
<button @click="addGroundSonProperty">新增孙子属性</button>
<button @click="addChildProperty">新增儿子属性</button>
<button @click="updateChildProperty">修改儿子属性</button>
<button @click="deleteChildProperty">删除儿子属性</button>
<button @click="deleteGrandsonProperty">删除孙子属性</button>
</div>
<div>
{{data}}
</div>
</div>
</template>
<script>
export default {
name: 'Home',
components: {
},
data(){
return {
data:{
child:{
grandson:"aaa"
},
child2:''
},
eventStr:''
}
},
watch:{
data(){
console.log('watch : ',this.eventStr);
alert('1');
}
},
methods:{
updateGroundSonProperty(){
this.eventStr = 'update grandson'
console.log(this.eventStr);
this.$set(this.data.child,'grandson','grandson');
},
addGroundSonProperty(){
this.eventStr = 'add grandson'
console.log(this.eventStr);
this.$set(this.data.child,'grandson2','grandson2');
},
addChildProperty(){
this.eventStr = 'add child'
console.log(this.eventStr);
this.$set(this.data,'child3','child3');
},
updateChildProperty(){
this.eventStr = 'update child'
console.log(this.eventStr);
this.$set(this.data,'child2','child2');
},
deleteChildProperty(){
this.eventStr = 'delete child'
console.log(this.eventStr);
this.$delete(this.data,'child2');
},
deleteGrandsonProperty(){
this.eventStr = 'delete grandson2'
console.log(this.eventStr);
this.$delete(this.data.child,'grandson2');
}
}
}
</script>