<template>
<div class="">
<div class="">{{ obj }}</div>
<div class="">{{ list }}</div>
<span class="ys-btn" @click="changeAge">改變年齡</span>
<span class="ys-btn" @click="addHeight">新增屬性height</span>
<span class="ys-btn" @click="changeList">改變list某值</span>
<span class="ys-btn" @click="addList">新增list一個值</span>
</div>
</template>
<script>
export default {
name:"ys_tooltips",
data(){
return {
obj:{
name:"躍焱邵隼",
age:17
},
list:['小華','曉麗','大大']
}
},
methods:{
changeAge(){
// this.obj.age="18" //可以這樣監聽對象/數組的屬性改變
this.$set(this.obj,'age',18); //Vue.set( target, key, value )
},
addHeight(){
// this.obj.height="180" //vue無法這樣監聽對象及數組的屬性新增/刪除;所以需要使用vm.$set的方式
this.$set(this.obj,'height',"180") //Vue.set( target, key, value )
},
changeList(){
this.$set(this.list,0,'小喬'); //Vue.set( target, key, value )
},
addList(){
this.$set(this.list,this.list.length,"小河") //Vue.set( target, key, value )
}
},
mounted(){
},
watch:{
obj:{
handler(newVal,oldVal){
this.ysvDirect.message({
type:'tip',//默認
msg:"obj is change:"+JSON.stringify(newVal),
face:'wow',//cry,smile,wow
// during:3000
})
}
,deep:true //深度監聽 監聽數組對象的屬性增刪改查
},
list:{
handler(newVal,oldVal){
this.ysvDirect.message({
type:'tip',//默認
msg:"obj is change:"+JSON.stringify(newVal),
face:'wow',//cry,smile,wow
// during:3000
})
}
,deep:true //深度監聽 監聽數組對象的屬性增刪改查
},
'obj.age':{ //只監聽 某個屬性的變化。避免深度深度監聽的深度遍歷開銷大;
handler(newVal,oldVal){
this.ysvDirect.message({
type:'tip',//默認
msg:"obj is change:"+JSON.stringify(newVal),
face:'wow',//cry,smile,wow
// during:3000
})
}
}
}
}
</script>
/********************/
總結:
1:vue監聽數組及對象屬性的增刪改查,應該使用深度監聽;
2:當數組/對象的屬性改變/新增時我們最好使用 this.$set()方法。而不是直接賦值的方法(this.obj.age='')因爲直接賦值的方法,對於新增屬性,vue監聽不到;
3:深度監聽,會深度遍歷;爲了減少開銷,必要情況下,我們只監聽相應某個屬性值的變化就行了。如上