Skip to main content
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