#Day 4: Methods, Computed And Watch Property || 30 Days of Vue

Rasel Hossain
Vue Expert
Published in
2 min readAug 24, 2021

--

Today we’ll take a look at the computed property, method, and watcher

Methods

We already use the method in previous articles. Methods are especially useful when you need to perform an action. Look like this.

<button @click="handleClick">Click</button>

Here “handleClick” will call when the element is clicked. A method is just a function where you can pass the value as a parameter, return a value, and many things you can do like a pure JavaScript function.

Let’s see some examples of Vue methods.

let’s see some examples…

HTML :
{{reverseData}}
<button v-on:click='reverseText'>Change User</button>
main.js
new Vue({
el:"#app",
data(){
return{
user:"RaselOfficial",
reverseData:""
}
},
methods:{
reverseText(){
console.log("hi")
this.reverseData= this.user.split("").reverse().join("")
}
}
})

This “textReverse” method is just revers a string.

In the method, if you want to access data property then we have to use this keyword before the data property

Computed Properties

A computed property is used to declaratively describe a value that depends on other values. It’s a property that calculates and returns a value. Computed properties are defined in the “computed” property of the Vue Component. And you can directly bind the computed property data in the template/HTML using “{{}}”

computed:{
}

Let’s reverse a string using the Computed property

HTML :
{{reversText}}
main.js :
new Vue({
el:"#app",
data(){
return{
user:"RaselOfficial",
}
},
computed:{
reversText(){
return this.user.split("").reverse().join("")
}
}
})

In the computed property the “reverText” value is dependent on the “user” data property. The key difference to using computed properties is that computed properties are cached based on the dependencies they depend on.

Here I highlight the main differences between using “methods” and “computed” properties

WATCHERS

The watch property in Vue will work when the specific data changes.Watch property take to value as a parameter 1.newValue 2.oldValue

For example, we have a count data property. Now we want when the count value will be more than 5 then we want to alert something, and at the same time, the count data property value will be 0.

Here to detect count value changes, we need “watch” property

So let’s see it…

HTML :
{{count}}
<button @click="handleCount">Click</button>
main.js :
new Vue({
el:"#app",
data(){
return{
count:0,
}
},
methods:{
handleCount(){
this.count+=1;
}
},
watch:{
count(newValue,oldValue){
if (newValue>5){
alert("count is more then 5")
this.count=0;
}
}
}
})

remember the watch property name and data property name should be the same when you want to use the watch property

--

--