Evento click en Vue.js

Author
By Darío Rivera
Posted On in Vue.js

Event handling in Vue.js can be done thanks to the v-on directive. To bind an event, simply use this directive followed by the event to be linked and the expression to be used. Let's see the syntax of this directive below.

v-on:event="expression"

Click Event

Since an expression can be used in the value of the property with this directive, a JavaScript statement or any function defined in the Vue instance can be executed. Let's see some examples that can be done with this event.

Expressions

Let's look at the following example where two numbers to be added are defined and a property that contains the result of this calculation.

var vue = new Vue({
 el: "#app",
 data: {
   n1: 0,
   n2: 0,
   sum: 0
 }
});

To see this example in action, we can use the following HTML.

<div id="app">
 Type the first number:
 <input type="number" v-model.number="n1"><br />
 Type the second number:
 <input type="number" v-model.number="n2"><br />
 <button v-on:click="sum = n1 + n2">Sum</button><br />
 The sum is: {{ '\{\{ sum \}\}' }}
</div>

Observe how this example works in Codepen.


As you can see, the expression used is sum = n1 + n2. When the value of the sum property is changed, the HTML is updated showing the result.

Methods

Now let's see that we can also place a function in the click event.

var vue = new Vue({
 el: "#app",
 data: {
   n1: 0,
   n2: 0,
   ans: 0
 },
 methods: {
   sum: function() {
     this.ans = this.n1 + this.n2;
   }
 }
});

With this, the HTML would change like this:

<div id="app">
 Type the first number:
 <input type="number" v-model.number="n1"><br />
 Type the second number:
 <input type="number" v-model.number="n2"><br />
 <button v-on:click="sum">Sum</button><br />
 The sum is: {{ '\{\{ ans \}\}' }}
</div>

You can see this example in action on Codepen.


Methods with Parameters

It is equally possible to use a function as a parameter in the click event expression as follows.

var vue = new Vue({
 el: "#app",
 data: {
   n1: 0,
   n2: 0,
   ans: 0
 },
 methods: {
   sum: function(a, b) {
     this.ans = a + b;
   }
 }
});
<div id="app">
 Type the first number:
 <input type="number" v-model.number="n1"><br />
 Type the second number:
 <input type="number" v-model.number="n2"><br />
 <button v-on:click="sum(n1,n2)">Sum</button><br />
 The sum is: {{ '\{\{ ans \}\}' }}
</div>

Next is the same example on Codepen.



Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.