← Back to Vue.js Course | Chapter 3: Reactivity | Lesson 3 of 7

Watchers

A watcher runs your code whenever a piece of data changes, which is useful for side effects like saving or fetching.

In this page:

  1. Watchers
Syntax
markup
export default {
  watch: {
    property(newValue, oldValue) {
      // react to the change
    }
  }
}

Watchers

The watch option maps a property name to a function receiving the new and old values. Watchers suit asynchronous or expensive reactions to change, while computed suits derived values. You can watch nested paths using quotes, such as "user.name".

Note: Prefer computed when you just need a derived value.

Example: Watchers

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <button @click="q = 'vue'">Search vue</button>
  <p>Query: {{ q }} | History: {{ history.join(", ") }}</p>
</div>
<script>
  Vue.createApp({
    data() { return { q: "", history: [] }; },
    watch: { q(newVal, oldVal) { this.history.push(`"${oldVal}" -> "${newVal}"`); } },
  }).mount("#app");
  document.querySelector("button").click();
  Vue.nextTick(() => console.log(document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: Search vueQuery: vue | History: "" -> "vue"
console: Query: vue | History: "" -> "vue"
-->
Live Example
Related Topics
Common Mistakes
  1. Using a watcher where computed would do
  2. Forgetting the old value is available
  3. Creating infinite loops by changing the watched value
Chapter Summary
  • watch reacts to changes
  • Receives new and old values
  • Good for side effects
  • Computed is better for derived data
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.