Computed Properties and Watchers

Understand Vue 2.0 reactivity and learn practical techniques for computed properties and watchers.

🎯 Introduction

This article explains the fundamentals of reactive data in Vue 2.0 and how computed properties and watchers make pages more responsive and efficient. These concepts are especially useful when starting frontend development, helping you write cleaner code with better performance.


🧱 What Is Reactivity in Vue 2.0?

You have probably encountered the term “reactivity” when learning Vue. Simply put, reactivity means that the page updates automatically when data changes. For example, when text entered in a form immediately appears in a nearby display area, reactivity is doing the work.

Vue 2.0 implements reactivity through data interception and a publish-subscribe pattern. When you change data, Vue notifies the parts of the application that use it and automatically updates the view.


⚙️ Computed Properties (computed)

Computed properties derive a new value from existing data and cache the result. They are recalculated only when their reactive dependencies change.

Benefits of Computed Properties:

  • Centralize logic and avoid duplicated code
  • Improve performance through automatic caching
  • Use derived values conveniently in templates

Example: A Basic Computed Property

example.vue
<template>
    <div>
        <p>Original message: {{ message }}</p>
        <p>Uppercase message (computed): {{ uppercaseMessage }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            message: 'hello vue',
        };
    },
    computed: {
        uppercaseMessage() {
            // Recalculate only when message changes
            return this.message.toUpperCase();
        },
    },
};
</script>
Computed properties are useful when you need to derive data from existing values and cache the result.

👂 Watchers (watch)

A watcher observes a data value and runs a callback whenever that value changes.

Watchers are useful for asynchronous operations or expensive tasks, such as making API requests.

Example: Using a Watcher

example.vue
<template>
    <div>
        <input v-model="question" placeholder="Enter your question" />
        <p>Answer: {{ answer }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            question: '',
            answer: 'Enter a question and wait a moment...',
        };
    },
    watch: {
        question(newQuestion) {
            if (newQuestion.indexOf('?') === -1) {
                this.answer = 'Questions usually need a question mark!';
                return;
            }
            this.answer = 'Thinking...';
            this.getAnswer();
        },
    },
    methods: {
        getAnswer() {
            setTimeout(() => {
                this.answer = 'This is a simulated answer.';
            }, 1000);
        },
    },
};
</script>
Use watchers to perform asynchronous operations or call functions in response to data changes.

🔍 Computed Properties vs. Watchers

Both respond to data changes, but they serve different purposes.

  • Computed properties derive new values from data and cache the results.
  • Watchers observe data changes and run complex or asynchronous operations in response.

Think of a computed property as an automatic calculator, and a watcher as an alarm that triggers a specific action when data changes.


❓ Questions and Answers

Q1: What is the main difference between computed properties and watchers?

Computed properties derive and cache values from data. Watchers run functions in response to data changes and are especially useful for asynchronous work.

Q2: When should you use a computed property or a watcher?

Use a computed property when you need derived data and efficient reuse of its value. Use a watcher when a data change should trigger side effects.


🧪 Exercises

Exercise 1

Create an input that accepts a number and displays its square using a computed property.

<template>
    <div>
        <input v-model="num" type="number" placeholder="Enter a number" />
        <p>Square: {{ square }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            num: 0,
        };
    },
    computed: {
        // Define the square computed property here
    },
};
</script>

Exercise 2

Create a text input that displays a warning when the text exceeds 10 characters. Implement this with a watcher.

<template>
    <div>
        <input v-model="text" placeholder="Enter some text" />
        <p v-if="warning" style="color: red;">The text is too long!</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            text: '',
            warning: false,
        };
    },
    watch: {
        // Watch text, check its length, and set warning
    },
};
</script>

🎉 You now understand reactivity, computed properties, and watchers in Vue 2.0!