0
0
Vueframework~10 mins

Watchers for side effects in Vue - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Watchers for side effects
Start Component
Declare reactive state
Set up watcher on state
State changes?
NoWait
Yes
Watcher runs side effect
Side effect updates DOM or logs
Wait for next change
The watcher observes a reactive state. When the state changes, it runs a side effect like updating the DOM or logging.
Execution Sample
Vue
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newVal) => {
  console.log(`Count changed to ${newVal}`)
})
count.value = 1
This code watches the reactive variable 'count' and logs a message whenever 'count' changes.
Execution Table
StepActionState BeforeState AfterWatcher Triggered?Side Effect Output
1Initialize countcount=undefinedcount=0NoNone
2Set up watcher on countcount=0count=0NoNone
3Change count.value to 1count=0count=1YesConsole logs: 'Count changed to 1'
4No further changescount=1count=1NoNone
💡 No more changes to reactive state, watcher does not trigger.
Variable Tracker
VariableStartAfter Step 1After Step 3Final
count.valueundefined011
Key Moments - 2 Insights
Why does the watcher run only after the state changes?
The watcher triggers only when the reactive variable changes value, as shown in step 3 of the execution_table where count changes from 0 to 1.
Does the watcher run when it is first set up?
No, the watcher does not run immediately on setup unless configured with immediate: true. Step 2 shows no watcher trigger.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of count after step 3?
A1
Bundefined
C0
Dnull
💡 Hint
Check the 'State After' column for step 3 in the execution_table.
At which step does the watcher trigger a side effect?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Watcher Triggered?' column in the execution_table.
If count.value changed to 2 after step 4, what would happen?
AWatcher does not trigger
BWatcher triggers and logs 'Count changed to 2'
CComponent re-renders but no log
DError occurs
💡 Hint
Watchers run side effects on reactive state changes as shown in step 3.
Concept Snapshot
Vue watchers observe reactive state changes.
When the watched value changes, the watcher runs a side effect function.
Side effects can update UI, log info, or trigger other actions.
Watchers do not run on setup unless immediate: true is set.
Use watchers to react to changes outside template rendering.
Full Transcript
This visual trace shows how Vue watchers work for side effects. First, a reactive variable 'count' is created with initial value 0. Then a watcher is set up to observe 'count'. When 'count.value' changes to 1, the watcher triggers and runs its side effect, logging the new value. The watcher does not run on setup or when there are no changes. This helps run code in response to state changes, like logging or updating external systems.