free
web stats

Vue Js 2 – Using Events

In this post, I want to show you how we can react to different types of events in Vue Js 2.In this post, I want to show you how we can react to different types of events in Vue Js 2.

Here is all js and html codes;

index.html file;

app.js file

 

I have a index.html file and app.js file. I’m going to a h1 tag in html file and then inside here I’m writing this code;

<h1>This animal is {{ animalName }}</h1>

In app.js file, I’m writing this code. I’m setting “dog” to animalName property.

new Vue({
    el:’#vue-app’,
    data: {
        animalName: ‘dog’
        }
)}

In browser we can this result;

This animal is dog.

Ok. I want to do is create a couple of buttons which is going to change its animalName. Here is my buttons in html.

<button>Cat Button</button>
<button>Horse Button</button>
<button>Dog Button</button>

That’s mean, When I’m going to click cat button, Write html This is a cat, or click horse, write This is a horse.

We need to listen to these DOM events, click events and we do that in Vue Js is by using the directive v-on. A directive is just something with popping like an instruction.

We can say what type of event; mouse over event, click event and etc. with v-on:click v-on:over …

We will use now v-on:click. After clik event, we are setting animal names.

<button v-on:click=”animalName=’cat'”>Cat Button</button>
<button v-on:click=”animalName=’horse'”>Horse Button</button>
<button v-on:click=”animalName=’dog'”>Dog Button</button>

Now go to browser and test it. When we click horse button, the text will change with horse and so on.
Now we can use click event in Vue Js 2.

You can use simply other mouse events like mouseover, mouseout etc..

Examples of events in Vue Js;

<a v-on:click=“doThis”></a>

<a v-on:click.stop=“doThis”></a>

<a v-on:mouseover=“doThis”></a>

<a v-on:mouseout=“doThis”></a>

<a v-on:submit=“doThis”></a>

<a v-on:click.once=“doThis”></a>

For much more examples and explanation, you can visit Vue Js events page;

https://vuejs.org/v2/guide/events.html

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *