2. Vue Events Handling and Methods
Every Vue.js application starts by creating a new Vue instance and you can create Vue Instance by usingnew Vue({})
and inside you can pass lots of properties. With data
(Object) property used to store the data for the Vue instance. Use {{ }}
to view the data from the Vue instance.
You can also check out the video on Event Handling and Methods here.
You can perform actions/events on Button with v-on:click="methodName()"
or @click="methodName()"
directive to listen to DOM events and run some JavaScript when they’re triggered.
There is one more property methods
that you can use for defining functions/methods for Vue Instance. and you can call the methods in HTML Page
<div id="app">
<p>{{a}}</p>
<button v-on:click="showAlert()">Show Alert</button>
</div><script>
new Vue({
el: "#app",
data:()=>({
a: 0
}),
methods: {
showAlert(){
alert('Hello')
}
}
})
</script>
Pass parameters to Vue.js methods
Methods can accept parameters.
In this case, you just pass the parameter while calling the method
<div id="app">
<button v-on:click="showAlert('something')">Show Alert</button>
</div><script>
new Vue({
el: "#app",
data:()=>({
}),
methods: {
showAlert(text){
alert(text)
}
}
})
</script>
How to access data from a method
You can access any of the data properties of the Vue component from the method by using this.propertyName
:
<div id="app">
<p>{{a}}</p>
<button v-on:click="incrementData()">+</button>
<button v-on:click="decrementData()">-</button>
</div><script>
new Vue({
el: "#app",
data:()=>({
a: 0
}),
methods: {
incrementData(){
this.a++
},
decrementData(){
this.a--
}
}
})
</script>
You don’t have to use it, this.data.a
just this.a
. Vue does provide a transparent binding for us. Using this.data.a
will raise an error.
You can also check out the video on Event Handling and Methods here.
You can find more info about Vue Events Handing and Methods at Vue Documentation.
Keep watching this and follow us for more tech articles or you can reach out to me for any doubt and suggestions and the next blog in the series will be published soon.
Thanks
Happy Coding!