Menu
CoddyTech

Watching a Ref

Part of the Fundamentals section of Coddy's Vue journey. Lesson 41 of 55.

A watcher performs a side effect when its source changes. This example records the previous category after a new category is selected; a computed value would be a better fit for pure derived display.

const category = ref('Art');
const previous = ref('None');
watch(category, (newValue, oldValue) => {
  previous.value = oldValue;
});

Pass the ref itself to watch, not its current primitive value. By default the callback waits for a change, and Vue batches reactive updates. Assigning the same primitive value again does not create a new transition. The callback receives new value first and old value second.

challenge icon

Challenge

Medium

Watch a topic ref initially Garden. Use a separate draft input #input, initially matching the topic. Show change count in #result as Changes: 0 initially and the previous value in #previous, initially None. Each actual source change adds one and remembers the old value; assigning the same value must not add another change. Do not run the watcher immediately.

Button #commit assigns the current draft to the watched source exactly once. Editing the draft alone must not count as a source change. Recommitting the same source value must not add a transition.

Try it yourself

<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals