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.

 

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon