Menu
CoddyTech

Watching Object Fields

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

To watch one property of a reactive object, pass a getter. This watcher runs for city changes without treating an edit to the person's name as a city change.

const person = reactive({ city: 'Lima', name: 'Nia' });
watch(() => person.city, (city, oldCity) => {
  console.log(oldCity, city);
});

Calling watch(person.city, ...) passes the current string and loses the reactive read. A getter lets Vue rerun that read and track its dependency. Watch the narrow source that matches the effect you need; watching the whole object can react to unrelated nested changes.

challenge icon

Challenge

Medium

Watch only the city property of the supplied reactive profile, initially Porto. Use a separate draft input #input, initially matching the city. 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. Bind #name to the unrelated name field initially Lee. Editing the name must not count as a city change.

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