Vue.js
Beginner
1 min read
Watchers: watch vs watchEffect
Example
<script setup>
import { ref, watch, watchEffect } from 'vue';
const userId = ref(1);
const profile = ref(null);
// ── watch: lazy, receives old + new ──────────
watch(userId, async (newId, oldId, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort()); // cancel prev fetch
const res = await fetch(`/api/users/${newId}`, { signal: controller.signal });
profile.value = await res.json();
console.log(`Changed from ${oldId} → ${newId}`);
});
// ── watch multiple sources ────────────────────
const page = ref(1);
const query = ref('');
watch([page, query], ([newPage, newQuery]) => {
console.log('Fetch page', newPage, 'query', newQuery);
});
// ── watchEffect: eager, auto-tracks ──────────
const log = ref([]);
watchEffect(() => {
log.value.push(`userId=${userId.value} page=${page.value}`);
});
// ── Immediate watch ───────────────────────────
watch(userId, (id) => console.log('immediate, id=', id), { immediate: true });
</script>