Vue Js Methods In Component Explained [ Updated 2020]

Hi today we are going to talk about methods in VueJS 2. So VueJs out of the box provides us some life cycle methods but we can define custom methods as well. In fact in most cases you will need to create custom methods.

Now in vue instance you can define methods like this as given below

 export default{
    data(){
      return{
        name:'Roger'
      }
    },
    methods:{
      myFirstMethod(){
        console.log('I Fire When You Call This Funtion');
      }
    },
    created(){
      this.myFirstMethod();
    }
  }

Now in code above we have a custom method "myFirstMethod". Which will console log some text. Notice that we are using "created" life cycle method to call our custom function. We can call our function in many ways using VueJs directives and On some page events. Have a look below.

 <template>
  <div>
    <button v-on:click="myFirstMethod($event)">Click Me To Fire Method</button>
  </div>
</template>

Here we can see on click of button our method will fire.

So ultimatly bottom line is this you can call your method as you want using life cycle methods or using directives. Its up-to what you really trying to get from your application.

For more practical demonstration check out this video tutorials about VueJS Methods.

https://youtu.be/_fXADT1wIdk

Let me know what approach you feel good. You prefer life cycle methods or you prefer custom methods.