VueJS Data & Methods Property

📆 Last updated Dec 13, 2019 👷 By, Chandan Tudu

In this tutorial, you will learn about VueJS data: & methods: property.

VueJS data: Property

The data: property is used to store dynamic data and this data can be of any type such as string, number, boolean, array, object, etc.

<div id="myApp">
  <ul>
    <li>{{string}}</li>
    <li>{{number}}</li>
    <li>{{boolean}}</li>
    <li>{{array[0]}}</li>
    <li>{{object.name}}</li>
  </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var myApp = new Vue({
    el:'#myApp',
    data:{
      string: 'This is a String',
      number: 75,
      boolean:true,
      array:['John','Mark','Barry'],
      object:{"name":"John Doe", "age":25, "email":"[email protected]"}
    }
});
</script>

VueJS methods: Property

The VueJS methods: property is used to store methods or functions.

<div id="myApp">
<!-- calling sayHello method -->
<p>{{ sayHello() }}</p>
</div>
var myApp = new Vue({
    el:'#myApp',
    methods:{
      sayHello: function(){
        return "Hello!";
      }
    }
});
Browser Output
Hello!

You can pass multiple methods or functions inside the methods: property.

var myApp = new Vue({
    el:'#myApp',
    methods:{
      sayHello: function(){
        return "Hello!";
      },
      anotherMethod(){
        return 'Another Method.';
      }
    }
});

How to pass arguments in a method?

<div id="myApp">
<!-- passing arguments inside the method -->
  <h1>{{ sayHi('John Doe') }}</h1>
</div>
var myApp = new Vue({
  el:'#myApp',
  methods:{
    sayHi: function(name){
      return "Hi, "+name;
    }
  }
});

How to access data: property inside a method?

you can access data: property using the this keyword.

<div id="myApp">
  <h1>{{ sayHi() }}</h1>
</div>
var myApp = new Vue({
  el:'#myApp',
  data:{
    name:"Barry"
  },
  methods:{
    sayHi: function(){
      return "Hi, "+this.name;
    }
  }
});

Leave a Reply

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