n Understand the difference between a watchers and a computed property in Vuejs | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Vue does provide a more generic way to observe and react to data changes on a Vue instance: watch properties.

When you have some data that needs to change based on some other data, it is tempting to overuse watch - especially if you are coming from an AngularJS background.

However, it is often a better idea to use a computed property rather than an imperative watch callback. Consider this example:

 

<div id="demo">{{ fullName }}</div>
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

 

The above code is imperative and repetitive. Compare it with a computed property version:

 

var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

Much better, isn’t it?

 

watch

Use watch when you want to perform asynchronous or expensive operations in response to changing data.

computed

Use computed in other cases. The computed properties are cached based on their dependencies. Mostly used when you want to only re-evaluate some of its dependencies have changed.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook