In this section, we will explore two powerful features of Vue.js: computed properties and watchers. These features allow you to create reactive data properties and respond to changes in your data model efficiently.

Computed Properties

Computed properties are properties that are derived from other data properties. They are cached based on their dependencies, meaning they will only re-evaluate when one of their dependencies changes. This makes them very efficient for complex calculations that depend on reactive data.

Key Concepts

  • Reactivity: Computed properties automatically update when their dependencies change.
  • Caching: Computed properties are cached until their dependencies change, making them efficient.
  • Declarative: Computed properties are declared in the computed option of a Vue instance.

Example

Let's look at a simple example to understand computed properties:

<div id="app">
  <p>Original Message: {{ message }}</p>
  <p>Reversed Message: {{ reversedMessage }}</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue.js!'
    },
    computed: {
      reversedMessage() {
        return this.message.split('').reverse().join('');
      }
    }
  });
</script>

Explanation

  • Data Property: message is a data property that holds the original message.
  • Computed Property: reversedMessage is a computed property that reverses the message string.

When the message changes, the reversedMessage will automatically update to reflect the reversed string.

Practical Exercise

Exercise: Create a Vue instance with a data property firstName and lastName. Add a computed property fullName that concatenates firstName and lastName.

Solution:

<div id="app">
  <p>First Name: {{ firstName }}</p>
  <p>Last Name: {{ lastName }}</p>
  <p>Full Name: {{ fullName }}</p>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      firstName: 'John',
      lastName: 'Doe'
    },
    computed: {
      fullName() {
        return this.firstName + ' ' + this.lastName;
      }
    }
  });
</script>

Watchers

Watchers are used to perform asynchronous or expensive operations in response to changing data. They allow you to "watch" a data property and execute a function when that property changes.

Key Concepts

  • Reactivity: Watchers respond to changes in data properties.
  • Asynchronous Operations: Watchers are useful for performing operations like API calls when data changes.
  • Declarative: Watchers are declared in the watch option of a Vue instance.

Example

Let's look at an example to understand watchers:

<div id="app">
  <p>Message: {{ message }}</p>
  <input v-model="message" placeholder="Edit the message">
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue.js!'
    },
    watch: {
      message(newValue, oldValue) {
        console.log(`Message changed from "${oldValue}" to "${newValue}"`);
      }
    }
  });
</script>

Explanation

  • Data Property: message is a data property that holds the message.
  • Watcher: The watcher on message logs the old and new values whenever message changes.

Practical Exercise

Exercise: Create a Vue instance with a data property counter. Add a watcher that logs a message whenever counter changes.

Solution:

<div id="app">
  <p>Counter: {{ counter }}</p>
  <button @click="counter++">Increment Counter</button>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      counter: 0
    },
    watch: {
      counter(newValue, oldValue) {
        console.log(`Counter changed from ${oldValue} to ${newValue}`);
      }
    }
  });
</script>

Summary

In this section, we covered:

  • Computed Properties: Efficiently derived properties that are cached based on their dependencies.
  • Watchers: Functions that respond to changes in data properties, useful for performing asynchronous or expensive operations.

Understanding and utilizing computed properties and watchers will help you create more reactive and efficient Vue.js applications. In the next section, we will explore class and style bindings in Vue.js.

© Copyright 2024. All rights reserved