watch()
Runs a callback when watched reactive sources change.
Syntax
watch(source, callback, options?): WatchHandle Parameters
| Name | Type | Required | Description |
|---|---|---|---|
source | Ref | getter | array | No | Reactive source(s) to observe. |
callback | (value, oldValue, onCleanup) => void | No | Invoked with new and old values on change. |
options | object | No | immediate, deep, flush, once. |
Returns
WatchHandle — A function/object to stop the watcher.
Examples
<script setup lang="ts">
import { ref, watch } from 'vue';
const query = ref('');
watch(query, async (q, _old, onCleanup) => {
const ctrl = new AbortController();
onCleanup(() => ctrl.abort());
const res = await fetch(`/api?q=${q}`, { signal: ctrl.signal });
console.log(await res.json());
});
</script>
Notes
Watch a ref directly, a getter `() => obj.prop`, or an array of sources. The
callback is lazy by default; pass `{ immediate: true }` to run on setup and
`{ deep: true }` to observe nested mutations of objects. Use onCleanup to
cancel stale async work.