watch
用來監聽某個值
watch(被監聽變數, (新值, 舊值) => {
要做的事...
});
ref
的值,那就直接監聽該值即可ref
物件的值,那要針對其中的資料,並將之改成 getter 可讀取的值,也就是 () => refObj.value.idx
這種方式ref
整個物件,那要加入第三個參數來做深層監控,也就是 {deep: true}
才行,無法取得舊值 reactive
物件的值,那要針對其中的資料,並將之改成 getter 可讀取的值,也就是 () => reactiveObj.idx
這種方式 reactive
整個物件,無法取得舊值watchEffect(()=>{})
用來監聽,且不須傳入欲監聽參數,只要在{}中直接使用參數值,就會自動監聽
watchEffect(() => {
console.log(num.value);
});
<script>
const { ref, reactive, watch, watchEffect } = Vue;
const App = {
setup() {
const num = ref(0);
const refObj = ref({ idx: 0 });
const reactiveObj = reactive({ idx: 0 });
let timer = null;
watch(num, (newNum, oldNum) => {
console.log(
"ref 資料" + num.value + " 的監控",
"新:" + newNum + ",舊:" + oldNum
);
});
watch(
() => refObj.value.idx,
(newNum, oldNum) => {
console.log(
"ref 單一物件 getter=" + refObj.value.idx + " 的監控",
"新:" + newNum + ",舊:" + oldNum
);
}
);
watch(
refObj,
(newNum, oldNum) => {
console.log(
"ref 整個物件=" + refObj.value.idx + " 的深層監控",
"新:" + newNum.idx + ",舊:" + oldNum.idx
);
},
{
deep: true,
}
);
watch(
() => reactiveObj.idx,
(newIdx, oldIdx) => {
console.log(
"reactive 單一物件 getter=" + reactiveObj.idx + " 的監控",
"新:" + newIdx + ",舊:" + oldIdx
);
}
);
watch(reactiveObj, (newObj, oldObj) => {
console.log(
"reactive 整個物件=" + reactiveObj.idx + " 的監控",
"新:" + newObj.idx + ",舊:" + oldObj.idx
);
});
watchEffect(() => {
console.log("watchEffect 監控 ref 資料 = " + num.value);
console.log("watchEffect 監控 ref 物件 = " + refObj.value.idx);
console.log("watchEffect 監控 reactive 物件 = " + reactiveObj.idx);
});
timer = setInterval(() => {
console.log("-------");
num.value++;
refObj.value.idx++;
reactiveObj.idx++;
if (num.value > 4) {
clearInterval(timer);
}
}, 2000);
return {};
},
};
Vue.createApp(App).mount("#app");
</script>
完整範例: