widgets Listening Events on VueJs (v-on)


Let’s listen and count click. Our Html looks like:

<div id="app">
    <button v-on:click="increase">Click Me</button>
    <p>{{counter}}</p>
</div>

v-on is listening events. This example we are listening click events with v-on:click and its equal increase method. Let’s look at the js part.

new Vue({
    el: '#app',
    data: {
        counter: 0,
    },
    methods: {
        increase: function() {
            this.counter++;
        }
    }
})

The counter is the variable that starts from 0 and each click will go increase method then add to +1 to counter variable.

Let’s listen and write coordinates in paragraph element. Create a paragraph element and listen mousemove:

<p v-on:mousemove="updateCoordinates">Cordinates:  {{ x }} / {{ y }}</p>

Then create updateCoordinates method listen event and update x, y data.

...
    data: {
        x: 0,
        y: 0
    },
    methods: {
        updateCoordinates: function(event) {
            this.x = event.pageX;
            this.y = event.pageY;
        }
    }
...

Notice: It can be possible to use “@” instead of “v-on:” in the html part. Example, “@click”