Computed properties looks like methods, but with some small difference.Let us see this simple example, so that you can understand computed propterties in better way.
<html>
<head>
<title>Computed properties in vuejs <title>
<script type=javascript src=vue.js>
<head>
<body>
<div id="computedprops">
Salutation: <input type="text" v-model="firstname" > <br>
LastName: <input type="text" v-model="lastname" > <br>
<h2>
My Name is {{salutation}} {{firstname}}
Computed name method: {{getnamewithsalutation}}
<h2>
<div>
<body>
<html>
<script type=text/javascript>
var vm=new vue({
el:'#computedprops',
data:{
salutation:"",
firstname:""
},
computed:{
getnamewithsalutation:function(){
return this.salutation +this.firstname;
}
}
});
when we type salutation and name in textbox,automatically gets reflected in the browser. and also computed property gets called automatically during the input of the textbox in the browser.
The method will be called as a function , whereas computed property will be called as a property. Let us see the following example to understand the difference between a method and a computed property.
<html>
<head>
<title>Difference between calling a method and computed property in vue <title>
<script type=javascript src=vue.js>
<head>
<body>
<div id="computedprops">
Salutation: <input type="text" v-model="firstname" > <br>
LastName: <input type="text" v-model="lastname" > <br>
<h2>
Call by Method: {{getnamewithsalutation()}}
Computed name property: {{getnamewithsalutation}}
<h2>
<div>
<body>
<html>
<script type=text/javascript>
var vm=new vue({
el:'#computedprops',
data:{
salutation:"",
firstname:""
},
Methods:
{
getnamewithsalutation:function()
{
return this.salutation + this.firstname;
}
},
computed:{
getnamewithsalutation:function(){
return this.salutation +this.firstname;
}
}
});
If you look into the get example, you can notice that whatever you changed in the input textbox,for eg, you have entered your name with salutation, get function will be called.It displays the name with salutation.Suppose if we pass name with salutation then it goes to setter function and splits by salutation and name.
<html>
<head>
<title>GET / SET in computed properties <title>
<script type=javascript src=vue.js>
<head>
<body>
<div id="computedprops">
Salutation: <input type="text" v-model="getnamewithsalutation" > <br>
<script type=text/javascript>
var vm=new vue({
el:'#computedprops',
data:{
salutation:"",
firstname:""
},
computed:
{
getnamewithsalutation:{
get:function()
{
return this.salutation +this.firstname;
}
set:function(name)
{
var items=name.split(" ");
this.salutation =items[0];
this.firstname = items[1];
}
}
}
Happy Vue Coding !!!