Computer scienceFrontendVue.jsComputable Properties

Watching for changes

6 minutes read

Vue watchers are an essential tool in the Vue.js framework that allows developers to reactively monitor and respond to changes in their data. These nifty functions act as a watchful eye, keeping track of specific data properties and executing custom logic when those properties change. Whether you're building a dynamic web application or just diving into Vue.js development, understanding Vue watchers is a key step to harnessing the power of this versatile framework. In this topic, we'll explore the power of Vue watchers, how to set them up, and various scenarios where they can greatly enhance your Vue.js projects.

Understanding vue watchers

In Vue.js, watchers are a core feature of the reactivity system that allows you to observe and respond to changes in a piece of data, such as a variable or a property of an object. Watchers enable you to perform specific actions when that data changes, without the need to continuously check for updates manually. This reactivity mechanism is fundamental for building responsive and dynamic user interfaces.

To create a watcher in Vue, you typically use the watch function. It takes two arguments: the data you want to watch and a callback function that specifies what action to take when the data changes. Watchers are particularly useful when you need to handle side effects, asynchronous operations, or respond to specific changes in your application's state. Whether it's monitoring user input, tracking changes in data fetched from an API, or responding to route changes, Vue watchers are an essential tool for building reactive and interactive web applications.

Creating and using watchers

To create a watcher using the Composition API, you can use the watch function. Here's an example of how to create a watcher for a reactive variable:

1. Defining a Data Property: Start by defining a reactive data property that you want to watch for changes. For example:

<script setup>
import { ref } from 'vue';

const count = ref(0);
</script>

2. Creating a Watcher: Next, create a watcher using the watch function:

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

watch(() => {
  // Logic to execute when 'count' changes
  console.log(`Count changed to ${count.value}`);
});
</script>

In the above example, the provided callback function will execute whenever the watched property (count in this case) changes. You can perform any custom logic within this function. Now, let's take an implementation of the above example to see the result of watchers and their behavior.

<template>
    <p>Count: {{ count }}</p>
    <button @click="incrementCount">Increment Count</button>
</template>

<script setup>
import { ref, watch } from 'vue'

const count = ref(0)

watch(() => {
  // Logic to execute when 'count' changes
  console.log(`Count changed to ${count.value}`)
})

const incrementCount = () => {
  count.value++
}
</script>

When you run the above Vue component, every time the count variable changes, the watcher's callback function will be executed, logging the new value to the console. This demonstrates how Vue watchers are a great tool for reacting to data changes and performing custom logic in response to those changes.

Watching array and object changes

Watchers can also be used to monitor changes within arrays and objects. When watching arrays, you can use the watch function with the deep option set to true to react to changes within the array's elements. Similarly, for objects, you can set the deep option to react to changes within object properties.

Here's an example of watching an array:

<template>
    <ul>
      <li v-for="item in items" :key="item">{{ item }}</li>
    </ul>
    <button @click="addItem">Add Item</button>
</template>

<script setup>
import { ref, watch } from 'vue';

const items = ref([1, 2, 3]);

watch(items, (newItems, oldItems) => {
  console.log('Items changed:', newItems);
}, { deep: true });

const addItem = () => {
  items.value.push(items.value.length + 1);
};
</script>

When you run the above code snippet, every time an item is added to the items array, the watcher's callback function will be executed, logging the new array to the console. We use the watch function to observe changes in the items variable with the deep option set to true. This means it will watch for changes inside the array as well. This demonstrates how Vue watchers with the deep option allow you to react to changes within arrays or objects.

Here's the result of the above code snippet:

Output  of watching an array via watchers

Here's an example of watching an object:

<template>
    <p>Person: {{ person.name }} is {{ person.age }} years old</p>
    <button @click="updatePerson">Update Person</button>
</template>

<script setup>
import { ref, watch } from 'vue';

const person = ref({
  name: 'Emma',
  age: 20
});

watch(person, (newPerson, oldPerson) => {
  console.log('Person changed:', newPerson);
}, { deep: true });

const updatePerson = () => {
  person.value.name = 'Jacob';
  person.value.age = 25;
};
</script>

Vue watchers work same for the objects as that of arrays. When you run the above Vue component, every time the properties of the person object change, the watcher's callback function will be executed, logging the updated object to the console.

Here's the result of the above code snippet:

Output  of watching an object via watchers

Watch vs computed

While computed properties are an effective way to derive values from reactive data, watchers are more suitable for tasks that involve side effects or asynchronous operations. Here are some key differences between watch and computed properties:

  • Watchers are more appropriate when you need to execute a function whenever a specific piece of data changes. This is useful for tasks like making HTTP requests, performing animations, or logging changes.

  • Computed properties are best when you want to derive a new value based on reactive data, and you want that value to be cached until its dependencies change. Computed properties are ideal for calculations and transformations that don't involve side effects.

Read more on this topic in Exploring Python Magic Method Operators on Hyperskill Blog.

Conclusion

Vue watchers are a crucial aspect of Vue.js development. They provide a way to reactively monitor and respond to changes in your data. Watchers are particularly valuable for handling side effects, asynchronous operations, and custom logic when data properties change. While computed properties are great for deriving values from data, watchers are the preferred choice when you need to react to data changes and perform custom actions.

2 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo