computed lifecycle method in Vuejs


We have seen some of the basic operations in vuejs . Now move on to advanced area. In the following example we will learn how to create computed properties.

For creating a dynamic counter ,which shows counter value while user clicking a button, we have to create

  • a button in template
  • event handler for button click
  • property for holding counter value
  • computed property for shouwing the value and bind it to the template
<template>
.........
{{getCounter}}
<button @click="clickHandler">
       Click me 
</button>
</template>

<script>
 
export default {
  
  name: "CounterComponent",
 
  data() {
    return {
    counter= 0
      }
  }, 
  methods: {
    clickHandler() {
      this.counter=this.counter+1;
      }   
  },
   computed: {
getCounter(){
return this.counter;
}
}
}
</script>

Data ()

The data holds the data for the component, where we can declare and initialize property, objects for model and binding.

methods

Methods contain a set methods that can be served for special purpose. We can declare event Handlers and function to process the data here.

computed

There are few lifecycle methods in vuejs, computed is one of them. We can declare functions inside the computed section ( only functions with return value), which uses the property declared in data .

Whenever the value of those property changed the computed functions will re-called and thus our component will get live values.

binding the property

We can use {{}} to bind the computed property in the template

{{getCounter}}

In our case when the counter value changed as a result of the the computed function/property.

The following vue post posts may help you

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.