[Medium] watch vs watchEffect
1. What are watch and watchEffect?
什麼是 watch 和 watchEffect?
watch 和 watchEffect 是 Vue 3 Composition API 中用來監聽響應式資料變化的兩個 API。
watch
定義:明確指定要監聽的資料來源,當資料變化時執行回調函式。
<script setup>
import { ref, watch } from 'vue';
const count = ref(0);
const message = ref('Hello');
// 監聽單一資料來源
watch(count, (newValue, oldValue) => {
console.log(`count 從 ${oldValue} 變為 ${newValue}`);
});
// 監聽多個資料來源
watch([count, message], ([newCount, newMessage], [oldCount, oldMessage]) => {
console.log('count 或 message 改變了');
});
</script>
watchEffect
定義:自動追蹤回調函式中使用的響應式資料,當這些資料變化時自動執行。
<script setup>
import { ref, watchEffect } from 'vue';
const count = ref(0);
const message = ref('Hello');
// 自動追蹤 count 和 message
watchEffect(() => {
console.log(`count: ${count.value}, message: ${message.value}`);
// 當 count 或 message 改變時,自動執行
});
</script>
2. watch vs watchEffect: Key Differences
watch 與 watchEffect 的主要差異
1. 資料來源指定
watch:明確指定要監聽的資料
const count = ref(0);
const message = ref('Hello');
// 明確指定監聽 count
watch(count, (newVal, oldVal) => {
console.log('count 改變了');
});
// 明確指定監聽多個資料
watch([count, message], ([newCount, newMessage]) => {
console.log('count 或 message 改變了');
});
watchEffect:自動追蹤使用的資料
const count = ref(0);
const message = ref('Hello');
// 自動追蹤 count 和 message(因為在回調中使用了)
watchEffect(() => {
console.log(count.value); // 自動追蹤 count
console.log(message.value); // 自動追蹤 message
});
2. 執行時機
watch:預設懶執行(lazy),只在資料變化時執行
const count = ref(0);
watch(count, (newVal) => {
console.log('執行'); // 只在 count 改變時執行
});
count.value = 1; // 觸發執行
watchEffect:立即執行,然後追蹤變化
const count = ref(0);
watchEffect(() => {
console.log('執行'); // 立即執行一次
console.log(count.value);
});
count.value = 1; // 再次執行