//父組件
<heart-wear-connection :isShouhuan="isShouhuan"></heart-wear-connection>
watch: {
getwear: function(a, b) {
console.log("修改后為:" + a);
if(a === 'y'){
this.$nextTick(function(){
this.isShouhuan = true
})
}else{
this.$nextTick(function(){
this.isShouhuan = false
})
}
}
},
computed:{
getwear() {
return this.$store.state.ifLinkWatchSuccess
}
},
子組件
<view style="font-size: 26upx;padding-top: 10upx;color: #999999;" v-if="!isShouhuan1">
未連接
</view>
<view style="font-size: 26upx;padding-top: 10upx;color: #30D969;" v-else>
已連接
</view>
props: {
isShouhuan: {
default: true,
type: Boolean
}
},
watch: {
isShouhuan: {
immediate: true, // 這句重要
handler (val) {
this.isShouhuan1=val
}
}
},
data() {
return {
isShouhuan1: this.isShouhuan,
}
},
使用watch時有一個特點,就是當值第一次綁定的時候,不會執行監聽函數,只有值發生改變才會執行。如果我們需要在最初綁定值的時候也執行函數,則就需要用到immediate屬性。
比如當父組件向子組件動態傳值時,子組件props首次獲取到父組件傳來的默認值時,也需要執行函數,此時就需要將immediate設為true
watch 里面還有一個屬性 deep,默認值是 false,代表是否深度監聽
當需要監聽一個對象的改變時,普通的watch方法無法監聽到對象內部屬性的改變,只有data中的數據才能夠監聽到變化,此時就需要deep屬性對對象進行深度監聽。
