[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 的主要差异