Complete Vue.js Course: Mastering from Basic to Advanced
Sobre a Aula

Using Watchers to React to Specific Changes

Hello, students! Welcome to Lesson 2 of Watchers in Vue.js. Today, we will learn how to use watchers to react to specific changes.

How to React to Specific Changes?

By default, watchers react to all changes in a property. However, you can use the deep parameter to react to specific changes.

The syntax for reacting to specific changes is as follows:

watch(property, callback, { deep: true }) {
  // code to react to the change
}

Where:

  • property is the property you want to watch.
  • callback is the function that will be executed when the property changes.
  • deep is an optional parameter that specifies whether changes should be tracked recursively.

For example, let’s consider the following component:

<template>
  <div>
    <input type="text" v-model="text">
    <p>{{ text }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: '',
    };
  },
};
</script>

In this component, the text property is watched. When the user changes the text, the watcher will run, and the user interface will be updated.

Now, let’s add the deep parameter to the watcher:

watch('text', function(oldValue, newValue) {
  // Update the user interface with the new value of the text
}, { deep: true });

With the deep parameter set to true, the watcher will also run when the user changes the text property of a nested object.

Examples of Using Watchers to React to Specific Changes

Here are some examples of how to use watchers to react to specific changes:

  • React to changes in an array:
watch('array', function(oldValue, newValue) {
  // code to react to the change
}, { deep: true });
  • React to changes in an object:
watch('object', function(oldValue, newValue) {
  // code to react to the change
}, { deep: true });
  • React to changes in a specific property of an array or object:
watch('array.name', function(oldValue, newValue) {
  // code to react to the change
}, { deep: true });

Challenge

Here’s a challenge for you:

  • Create a component that displays a list of items. Use a watcher to update the list when the user adds a new item.

Good luck!

Tip

You can use the following code as a starting point:

<template>
  <div>
    <ul>
      <li v-for="item in items">{{ item }}</li>
    </ul>
    <input type="text" v-model="newItem">
    <button @click="addItem()">Add Item</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
      newItem: '',
    };
  },
  methods: {
    addItem() {
      this.items.push(this.newItem);
    },
  },
};
</script>

In the next topic, we will learn about templates in Vue.js. Templates are the way to define the structure and content of a Vue.js component.

Entrar na conversa
Rolar para cima