1.方式一:監(jiān)聽單個(gè)基本數(shù)據(jù)類型(ref),(ref定義的基本類型使用watch監(jiān)聽時(shí)候不需要.value)
watch(sum, (newVal, oldValue) => {
? ? ? ? console.log(newVal, oldValue);
? });
2.方式二:監(jiān)多個(gè)基本數(shù)據(jù)類型(ref)
watch([sum, tips], (newVal, oldValue) => {
? ? ? console.log(newVal, oldValue);// [121, 'a'],[78, 'b']監(jiān)聽結(jié)果新的值和舊的值都是數(shù)組
? ? });
3.監(jiān)聽對象(reactive),不建議使用
watch(state,(newVal, oldValue) => {
? ? ? ? console.log(newVal, oldValue);? //{name: '老王', age: 23},{name: '老王', age: 23}
? ? ? },
? ? ? { deep: false }
? ? );
4.監(jiān)聽對象中某一個(gè)屬性變化(reactive),強(qiáng)烈建議使用此方式監(jiān)聽reactive響應(yīng)對象數(shù)據(jù)(無坑)
watch(() => state.count, (newVal, oldValue) => {
? ? ? ? ? console.log(newVal, oldValue);
? ? ? }
? ? );
5.監(jiān)聽對象中某幾個(gè)屬性(reactive),建議使用
watch([() => obj.test, () => obj.year], (newVal, oldValue) => {
? ? ? console.log(newVal, oldValue);? //得到的是對象
? ? ? }
? ? );