本文章僅供個人學習記錄所用
監(jiān)聽 ref 類型
第一個參數(shù)是響應式對象,第二個參數(shù)是回調函數(shù)
const a = ref(0)
watch(a, (newVal, oldVal) => {
console.log(newVal, oldVal)
})
監(jiān)聽 reactive 類型
首先采用 ref 的那種方式,我們會發(fā)現(xiàn)報錯
const data = reactive({
count: 0
})
watch(data.count, (newVal, oldVal) => { // 錯誤寫法
console.log(newVal, oldVal)
})

錯誤信息
[Vue warn]: Invalid watch source: 0** A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types. **
所以我們根據(jù)上述的報錯信息,將這個參數(shù)改成一個 function的形式即可
const data = reactive({
count: 0
})
watch(() => data.count, (newVal, oldVal) => {
console.log(newVal, oldVal)
})
同時監(jiān)聽多個
watch 第一個參數(shù)可以使用數(shù)組的形式
watch([a, () => data.count], (newVal, oldVal) => {
console.log(newVal, oldVal)
})
watchEffect的使用
// watchEffect 監(jiān)聽
watchEffect(() => {
console.log(a.value, data.count) // ref 類型的需要加.value
})
??watch和watchEffect的特性對比
watch的特性
- 首次加載不會監(jiān)聽,只會被監(jiān)聽數(shù)據(jù)發(fā)生變化時才監(jiān)聽到。(惰性)
- 可以拿到新的值以前的值
- 可以同時監(jiān)聽多個數(shù)據(jù)的變化
watchEffect的特性
- 首次加載就會監(jiān)聽
- 只能拿到最新的值
- 不需要指定監(jiān)聽的數(shù)據(jù),組件初始化的時候就會執(zhí)行一次用以收集依賴,而后收集到的依賴發(fā)生變化,這個回調才會再次執(zhí)行
高級用法
他們的高級用法等后面應用的時候單獨再記錄下
完整案例代碼體驗
<template>
<div>
<h1>count :{{ count }}</h1>
<h1>a :{{ a }}</h1>
<button @click="increase">新增</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, toRefs, watch, watchEffect } from 'vue';
export default defineComponent({
name: 'HelloWorld',
setup() {
let a = ref(0)
const data = reactive({
count: 0,
increase: () => { data.count ++; a.value += 2 } // 這是改變兩個類型數(shù)據(jù)的方法
})
// watch 監(jiān)聽
watch([a, () => data.count], (newVal, oldVal) => {
console.log(newVal, oldVal)
})
// watchEffect 監(jiān)聽
watchEffect(() => {
console.log(a.value, data.count) // ref 類型的需要加.value
})
const refData = toRefs(data)
return {
...refData,
a
}
}
});
</script>