techferment
Published in

techferment

2. Vue Events Handling and Methods

Every Vue.js application starts by creating a new Vue instance and you can create Vue Instance by using and inside you can pass lots of properties. With (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 or directive to listen to DOM events and run some JavaScript when they’re triggered.

There is one more property 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 :

<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, just . Vue does provide a transparent binding for us. Using 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!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vrijraj Singh

Google Developer Expert for Web Technologies & Firebase | Developer Advocate | GDG Organizer for GDG Jalandhar