Stopbyte

What is the difference between Methods and Computed proprieties in Vuejs?

A few months ago, I started to use Vuejs framework, it was soo simple and easy for me to learn the framework, but sometimes I get confused and wonder whether to use methods or computed since they are very similar and could be used to do the same things many times but at the same time they are very different and need to be used in different ways.

the Difference is HUGE, yes they have many things in common but the way they handle data is widely different.

How different are computed and methods and when to use them?!

Methods?

They are static functions usually used to react to events that happen in the DOM and they accept arguments.
They are often used to run a functionality from the DOM as well, in addition to being widely used to make some reusable Logic, they are the choice for Handling Events and reacting to them.

i.e: When you want to show/hide an element at the click of a button.
i.e: When you want to pass arguments as parameters to your function.

Imagine this as where you won’t be able to see your score until you click a button!

Computed properties?

They don’t accept arguments, helpful to compose new data from existing sources
they get dynamic values based on other properties.
Computed properties are based on each system that tracks your data and only interacts when changes are made to the properties it is watching.

Imagine this as a game, but this time the score is Live (and Updated) on the screen and changes when some properties have changed (new level reached), without the need to click a button.

i.e: When you want to keep a value updated according to another value.
i.e: when you want to return a value according to the value you already got.

Computed properties are often used to:

  • Do calculation and at the end to return a value.
  • Only interact when a value or prop has changed.

Example of a Computed Property:

var vm = new Vue({ 
  el: '#vue-app', 
  data: { 
    firstname: 'Foo', 
    lastname: 'Bar' 
  }, 
  computed: { 
    fullname: function() { 
      return this.firstname + ' ' + this.lastname; 
    } 
  } 
})

Computed properties are cache-based, this means the function will run only once and will wait until the values have changed again, or if it’s called many times in the same template.

data: function() {
  return {
    counterComputed: 0,
    counterMethod: 0
  };
},
computed: {
  printTextComputed: function() { 
    console.log(“counter printed from computed:”,     
    this.counterComputed);
  }
},
methods: {
  printTextMethod: function() {
    console.log(“counter printed from method:”, this.counterMethod);
  }
},

above we set two counters, counterComputed that will be updated from the computed button and the counterMethod that will be updated from the method button.
Then in your computed and your methods, you simply console log the counters we have set.

#HTML

<div>
  <button @click=”counterComputed++”>computed button</button>
  <p>{{ counterComputed }}</p> <br/>
  <button @click=”counterMethod++”>method button</button>   
  <p>{{ counterMethod }}</p> <br/>
  {{ printTextMethod() }}
  {{ printTextComputed }}
</div>

Here we simply have the buttons that will update the counters, you render the counters near the buttons and you call the method and the computed only once per each.

RESULT:

If you followed the code you can see that when you click the computed button both the functions printTextComputed() and printTextMethod() are running but when you click the method button only the function printTextMethod() will runs.

Computed properties Vs Watched Property?

The watch version of a function that returns the Full Name of a person:

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
    }
  }
})

Now, this the Same function but using a Computed Property:

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

using a Watched Property like the one above is imperative and repetitive.

CONCLUSION:

  • methods: they need to run every time to check if the values used withing have changed because they don’t know since they are not cached based on their reactive dependencies..
  • computed properties: they know if the values used in the function changed so they don’t need to run every time to check. So they run only once and then watch the values so they are cached based on their reactive dependencies.
    A computed property will only re-evaluate when some of its reactive dependencies have changed.

so if wanted a function that will iterate an array of posts and then return the Most Liked posts what are you going to use? Methods or Computed properties?

1_T1VKMoCVuEPLIeUKaUqIAQ

Yep, a Computed Property since it only has to run Once and wait until more posts have been added to your Array or have been created.
But if you used a Method the function will be called whenever a re-render happens.
multiple access to the a computed property will immediately return the previously computed result without having to run the function again since it’s cached based.

→ Remember that Computed properties don’t accept arguments!

So when to use methods and when to use computed properties?

When to use METHODS?

  • To call a function when an event happens in the DOM.
  • To call a function from the computed or watchers when something happens in your component.
  • When you need to pass parameters.
  • When you want to handle events.
  • When you are dealing with a big amount of data.
  • In cases where you do not want caching, use a method instead.

When to use COMPUTED PROPERTIES?

  • When you want to watch your values and keep them updated.
  • When you want to return a new value based on the values you already have.
  • When you need to compose new data from existing data sources.
  • You need to reference a value directly in your template.
  • You call the same function more than once in your template.
  • you want to re-evaluate when some of your reactive dependencies have changed.

Aside Notes:

Remember the following computed property will never update, because Date.now() is not a reactive dependency:

computed: {
  now: function () {
    return Date.now()
  }
}

→ It depends on your needs and your project whether to use a method or a computed property.

Hope you learned something new :grinning:

1 Like