Vue.js Methods Property

Vue.js Methods

A Vue.js method is a function associated with the Vue.js instance. Methods are defined inside the `methods` property.

Let’s see how they work.

  1. What are Vue.js methods
  2. Pass parameters to Vue.js methods
  3. How to access data from a method

1) What are Vue.js methods

  • A Vue.js method is a function associated with the Vue.js instance.
  • A Vue.js  method is an object or function associated with the Vue.js instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.

Methods are defined inside the methods property:

Syntax:

export default { 
          methods: { 
              // We can add our functions here 
          }
}

Example:

<template>
 <a @v-on:click="handleClick">Click me!</a>
</template>

<script>
export default{
      methods : {
           handleClick: function(){
                  return alert("methods example of vue.js");
            }
      }

}
</script>

2) Pass parameters to Vue.js methods

  • Methods can accept parameters.
  • In this case, you just pass the parameter in the template.
<template>
  <a v-on:click="handleClick('Hey this is example of methods property')">Click me!</a>
</template>

<script>
export default {
  methods: {
    handleClick: function(data) {
     return alert(data);
    }
  }
}
</script>

3) How to access data from a methods

  • You can access any of the data properties of the Vue.js component by using this.proprtyname:
<template> 
   <div id="methodExample"> 
   <h3>Name:{{name}}</h3> 
   <h4>Topic:{{topic}}</h4> 
   <button v-on:click="onClick">Go to Example</button>
   </div> 
</template>

<script> 
export default{
    name : 'methodExample',
    data : function(){ 
        return{ 
            name :'Methods Example', 
            title :'Vue.js' 
        }
    },
    methods : { 
       onClick : function(){
             return alert("Hey! This is" + this.name + "of" + this.title); 
       } 
   } 
} 
</script>

For accessing the variables, we don’t have to use this.data.name, just this.name. Vue.js does provide a transparent binding for us. Using this.data.name will raise an error.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories