Vue JS 2 Data & Methods


In the last page, we bind some data and print on the home screen using Vue instance.  lest add methods and function.

new Vue({
    el: '#vue-app', 
    data: {
        name:'CoderMen',
    },

    methods:{
        greet: function() {
            return 'Hello Coder'
        }
    }
    
});

Here we create a function named greet in methods and that function simply returns a message "hello coder".  Now we use this function on our view page (On HTML page).

  <body> 
    <div id="vue-app">
       <h3>{{greet()}} </h3>
        <h3>{{name}} </h3>
      
    </div>
    <script src="app.js"></script>
  </body>

Result in something like this

Parameter use in Vue js Function

Use Parameter in Vue JS function

In this part, we learn how to send parameter in Vue Js function. 

Index.html

<body> 
    <div id="vue-app">
       <h3>{{greet('Mike')}} </h3>
       
    </div>
    <script src="app.js"></script>
</body>

App.js

new Vue({
    el: '#vue-app', 
   

    methods:{
        greet: function(name) {
            return 'Hello' +" " + name
        }
    }
    
});

 

Result

vue js 2 tutorials 

Next, we can also access data inside the Vue instance in this function using this keyword this. here is an example.

new Vue({
    el: '#vue-app', 
   
   	data:{
   		name: 'Peter'
   	},

    methods:{
        greet: function(name) {
            return 'Hello' +" " + name + " " + this.name
        }
    }
    
});

 

vue Js 2 tutorials method and data binding

 So we can see Peter is come from data to greet function from Vue instance.