Computed vs Watch properties in Vue.js

Computed vs Watch properties in Vue.js

Computed and Watch properties are both properties in Vue.js that work differently and of course are used for different purposes. Understanding how these properties work and knowing when to use them will help a developer leverage on the functionalities of Vue to its full potential. Moving forward, I'll discuss each property one after the other.

Computed property

Vue JS computed property is very much valuable for manipulating data that already exist, it is more like a lifesaver. As a Vue developer, when you are building something where you have to write a lot of logic in the template which might be used in multiple places in your code, the computed property comes in handy.

Let's take a look at this example:

Computed property not in use

<div id="example">
<p> Text: {{ text }}</p>
<p> Reversed Text: {{ text.split(' ').reverse().join(' ').toUpperCase() }}
</div>

Computed property in use

<div id="example">
<p> Text: {{ text }}</p>
<p> Reversed Text: {{ reversedText }}
</div>
export default {
   data () {
      text: 'Hi there!'
   },
computed: { 
    reversedText() {
       return this.text.split(' ').reverse().join(' ').toUpperCase() 
   }
}
// Result will give !EREHT IH

With this, there will be no annoying cluster of logic in the template.

Computed property is cached based on their reactive dependencies and will only be updated when needed. This means that as long as text has not changed, multiple access to reversedText will immediately return the previously computed result without having to run the function again.

Watch property

Vue JS Watch property observes reactive properties i.e. changing properties and can detect when there is a change. This is useful when performing asynchronous or expensive operations in response to changing data. In more simpler terms, watch property acts as an event listener to our component's reactive data.

How to use watch property

To use the watch property, you must first have a property in your data that you want to track, then declare a function with the same name as the property you want to observe. Check out the example below, it will give you a clearer picture.

export default {
    data () {
        return {
            name: ' ',
            fullname: ' ',
        }
 },
watch () {
    name(value) {
        this.fullname = value + " " + "Etok"
   }
}
    }

NB: We did not return the watch property, this is because it will not be used in the template.

The watch property can also accept two arguments, e.g

export default {
    data () {
        return {
            name: ' ',
            description: ' '
        }
    },
watch: {
    title: (firstName, lastName) => {
        console.log("Name changed from " + firstName + " to " + lastName)
    }
 }
}

Conclusion

I hope this has given you a basic understanding of computed and watch properties and how to use each of them.

Reference