watch的偵聽數據源類型
watch的第一個參數為偵聽數據源,有4種"數據源":
ref(包括計算屬性)
reactive(響應式對象)
getter函數
多個數據源組成的數組。
//ref
const x=ref(0)//單個ref
watch(x,(newX)=>{console.log(`x is ${newX}`)
})
//getter函數
const x = ref(0)
watch(
()=> x.value,
(newX)=>{console.log(`x is ${newX}`)}
)//getter函數const obj = reactive({count:0})
watch(
()=> obj.count,
(count)=>{console.log(`count is ${count}`)}
)
//reactive 隱式創建一個深層偵聽器const obj = reactive({count:0});
watch(obj,
(newV,olbV)=>{// 在嵌套的屬性變更時觸發// 注意:`newV` 此處和 `oldV` 是相等的// 因為它們是同一個對象!},
)//或者
watch(
()=>obj.count,
()=>{// 僅當 obj.count被替換時觸發}
)
// 多個來源組成的數組
const x=ref(0)
const y=ref(0)watch([x, () => y.value], ([newX, newY]) => {console.log(`x is ${newX} and y is ${newY}`)
})
watch屬性:
{ deep: true }? //強制轉成深層偵聽器,
深度偵聽需要遍歷被偵聽對象中的所有嵌套的屬性,當用于大型數據結構時,開銷很大。因此請只在必要時才使用它,并且要留意性能。
{ immediate: true } //強制偵聽器回調立即執行
{ once: true } // 3.4+,回調只在源變化時觸發一次