Watchers
A watcher is a function that runs when a value changes. Vue calls the watcher with the new value and the old value.
Watch a ref
The message starts as Waiting.
import { ref, watch } from 'vue'
const count = ref(0)
const message = ref('Waiting')
watch(count, (newValue) => { message.value = 'Count is ' + newValue })New value and old value
The log starts as none.
import { ref, watch } from 'vue'
const count = ref(0)
const log = ref('none')
watch(count, (newValue, oldValue) => { log.value = oldValue + ' to ' + newValue })A watcher sets a second value
The doubled value starts at 0.
import { ref, watch } from 'vue'
const count = ref(0)
const doubled = ref(0)
watch(count, (newValue) => { doubled.value = newValue * 2 })Example
<script setup>
import { ref, watch } from 'vue'
const count = ref(0)
const message = ref('Count has not changed yet')
watch(count, (newValue) => {
message.value = 'Count is now ' + newValue
})
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>{{ message }}</p>
</div>
</template>
Key points
- Call watch with the value to follow and a function to run.
- The function receives the new value first and the old value second.
- Use watch for follow-up work, like showing a message.
- The watcher does not run when the page first shows.
- It runs only after the watched value changes.
In this example, the script makes a count of 0 and a message. It watches the count with watch. The watcher builds a message from the new value. The page first shows Count: 0 and Count has not changed yet. The watcher does not run on the first show. When the count changes to 1, the message becomes Count is now 1.
Note
watch can follow one value or a list of values.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does a watcher run?