1. 監聽基本屬性
变更前,变更后。。。
let num = ref(1);
watch(num, (newValue, oldValue) => {
console.log(newValue, oldValue);
});
2. 監聽多個屬性
import { ref, watch } from "vue";
let num1 = ref(1);
let num2 = ref(2);
watch([num1, num2], ([newNum1, newNum2], [oldNum1, oldNum2]) => {
console.log(newNum1, newNum2, oldNum1, oldNum2);
});
3. 監聽對象屬性
const obj = reactive({ count: 0 })
// 提供一个 getter 函数
watch(
() => obj.count,
(count) => {
console.log(`Count is: ${count}`)
}
)
4. 深层监听
watch(
() => state.someObject,
(newValue, oldValue) => {
// 注意:`newValue` 此处和 `oldValue` 是相等的
// *除非* state.someObject 被整个替换了
},
{ deep: true }
)
5. 即時回調监听
watch(
source,
(newValue, oldValue) => {
// 立即执行,且当 `source` 改变时再次执行
},
{ immediate: true }
)