使用watch時有一個特點,就是當值第一次綁定的時候,不會執行監聽函數,只有值發生改變才會執行。如果我們需要在最初綁定值的時候也執行函數,則就需要用到immediate屬性。
handler方法和immediate屬性
當父組件向子組件動態傳值時,子組件props首次獲取到父組件傳來的默認值時,也需要執行函數,此時就需要將immediate設為true
之前我們寫的 watch 方法其實默認寫的就是這個handler,Vue.js會去處理這個邏輯,最終編譯出來其實就是這個handler。
immediate:true代表如果在 wacth 里聲明了 viewDetials之后,就會立即先去執行里面的handler方法,如果為 false就跟我們以前的效果一樣,不會在綁定的時候就執行
deep屬性
watch 里面還有一個屬性 deep,默認值是 false,代表是否深度監聽當需要監聽一個對象的改變時,普通的watch方法無法監聽到對象內部屬性的改變,只有data中的數據才能夠監聽到變化,此時就需要deep屬性對對象進行深度監聽。
設置deep: true 則可以監聽到newTemplateForm 的變化,此時會給newTemplateForm 的所有屬性都加上這個監聽器,當對象屬性較多時,每個屬性值的變化都會執行handler。如果只需要監聽對象中的一個屬性值,則可以做以下優化:使用字符串的形式監聽對象屬性:'newTemplateForm .cycleUpkeep'
newTemplateForm: { handler(val) { // 頻次任務 table 是否為數組
if (!Array.isArray(val.cycleUpkeep)) { this.newTemplateForm.cycleUpkeep = [{ dayNum: 1, timeStart: '', timeEnd: '' }] } // 次數大於table數據條目數
if (val.cycleUpkeep.dayNum > val.cycleUpkeep.length) { console.log(1111) for (var i = this.newTemplateForm.cycleUpkeep.length + 1; i <= this.newTemplateForm.cycleUpkeep.dayNum; i++) { this.newTemplateForm.cycleUpkeep.push({ dayNum: i, timeStart: '', timeEnd: '' }) } } // 時間間隔為 undefined 時
if (!this.newTemplateForm.cycleTypeNum) { this.newTemplateForm.cycleTypeNum = 1 } // 時間單位 可能為 0:天
if (!this.newTemplateForm.cycleType) { if (this.newTemplateForm.cycleType === 0) { this.newTemplateForm.cycleType = 0 } else { this.newTemplateForm.cycleType = 1 } } // 次數為 undefined 時
if (!this.newTemplateForm.cycleUpkeep.dayNum) { this.newTemplateForm.cycleUpkeep.dayNum = 1 } }, immediate: true, deep: true },
viewDetials: { handler(val) { console.log(val) }, immediate: true, }