v-on directive to bind event listeners to DOM events.
<div id="example"> <button v-on:click="clickme">Add 1</button> <p>The button above has been clicked {{ counter }} times.</p> </div>
var example1 = new Vue({ el: '#example', data: { counter: 0 }, methods : { clickMe : function(){ this.counter += 1; } } })We are binding a click event listener to a method named
clickMe
. Here’s how to define that method in our Vue instance. Here we have a counter variable initialized to zero. Inside the method, we are incrementing the value of the counter. So for each click on the button, the method is invoked. You will get the code here.
<div id="example2"> <button v-on:click="countUp">Count Up</button> <button v-on:click="countDown">Count Down</button> <h1>Count: {{ counter }}</h1> </div>
var example2 = new Vue({ el: '#example2', data: { counter: 0 }, methods : { countUp : function(){ this.counter += 1; }, countDown : function(){ this.counter -= 1; } } })Here in this example, we are using two button and methods. One for incrementing the count and other for decrementing. You can see code here. Note :-
Instead of using "v-on:click", we have a shortcut. We can use "@click".For example,
<div id="example2"> <button @click="countUp">Count Up</button> <button @click="countDown">Count Down</button> <h1>Count: {{ counter }}</h1> </div>This will give same result as before. We can see another example. Here we have an input field where we type the url which is bound to the Js using
v-model
. We have a button with click event listener which is bound to the method humanizeUrl
. We have two urls, url and cleanUrl. url is what we type in the input field and cleanUrl is getting by replacing the url using regular expression. Regular expression is not a Vue.js thing. Its a universal programming format. We are saving the domain name of url in the cleanUrl. Thus we will get the value on cleanUrl in the view. You will get the code here.
<div id="example"> Visit : <a href="#">{{cleanUrl}}</a><br><br> <input type="text" v-model="url" placeholder="Type your Url"> <button @click="humanizeUrl">humanizeUrl</button> </div>
var example1 = new Vue({ el: '#example', data: { url: "", cleanUrl: "" }, methods : { humanizeUrl: function(){ this.cleanUrl = this.url.replace(/^https?:\/\//, '').replace(/\/$/, '') } } })But here you won’t redirect to the url when we click on it. That is we have to get the url. So we need to bind the
href
. You can use v-bind
directive for this.
<div id="example"> Visit : <a v-bind:href="url">{{cleanUrl}}</a><br><br> <input type="text" v-model="url" placeholder="Type your Url"> <button @click="humanizeUrl">humanizeUrl</button> </div>Here is the Demo. So the url will redirect to the correct page. You can try out these examples to get an idea about event listeners in Vue.js.