n Understand the difference between a method and a computed property | 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:

Computed values and methods are very different in Vue and are definitely not interchangeable in most cases.

Computed Property

A more appropriate name for a computed value is a computed property. In fact, when the Vue is instantiated, computed properties are converted into a property of the Vue with a getter and sometimes a setter.

Basically you can think of a computed value as a derived value that will be automatically updated whenever one of the underlying values used to calculate it is updated.

You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Here's the classic example from the documentation:

 

computed: {
  // a computed getter
  reversedMessage: function () {
    // `this` points to the vm instance
    return this.message.split('').reverse().join('')
  }
}

 

Which is referenced in the DOM like this:

<p>Computed reversed message: "{{ reversedMessage }}"</p>

 

Computed values are very valuable for manipulating data that exists on your Vue. Whenever you want to filter or transform your data, typically you will use a computed value for that purpose.

 

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.names.filter(n => n.startsWith("B"))
    }
}

<p v-for="name in startsWithB">{{name}}</p>

Computed values are also cached to avoid repetitively calculating a value that doesn't need to be re-calculated when it hasn't changed (as it might not be in a loop for example).

 

Method

A method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. Like all javascript functions it accepts parameters and will be re-evaluated every time it's called. Methods are useful in the same situations any function is useful.

 

data:{
    names: ["Bob", "Billy", "Mary", "Jane"]
},
computed:{
    startsWithB(){
        return this.startsWithChar("B")
    },
    startsWithM(){
        return this.startsWithChar("M")
    }
},
methods:{
    startsWithChar(whichChar){
        return this.names.filter(n => n.startsWith(whichCharacter))
    }
}

computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

If you want data to be cached use Computed properties on the other hand if you don't want data to be cached use simple Method properties.

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