Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue.js Event Handlers

Vue.js Event Handlers

Event listening can use the v-on directive:

v-on

<div id="app">
<button v-on:click=">

counter += 1

"

Increment by 1

button

<

p

This button has been clicked {{ counter }} times.

p

div

<

script

new Vue({ el: '#app', data: { counter: 0 } })

script

Try it »

Usually, we need to use a method to invoke a JavaScript method.

v-on can accept a defined method to call.

v-on

<div id="app">
<button v-on:click="greet" Greet button div>
<script>

var app = new Vue({ el: '#app', data: { name: 'Vue.js' }, // in methods define methods in the object methods: { greet: function (event) { // this inside a method refers to the current Vue instance alert('Hello ' + this.name + '!') // event is the native DOM event if (event) { alert(event.target.tagName) } } } }) // you can also call the method directly with JavaScript app.greet() // -> 'Hello Vue.js!'

script

Try it »

Besides directly binding to a method, you can also use inline JavaScript statements:

v-on

<div id="app">
<button v-on:click="say('hi')">

Say hi

button

<button v-on:click="say('what')">

Say what

button

div

<

script

new Vue({ el: '#app', methods: { say: function (message) { alert(message) } } })

script

Try it »

Event Modifiers

Vue.js provides event modifiers for v-on to handle DOM event details, such as event.preventDefault() or event.stopPropagation().

Vue.js invokes modifiers via directive suffixes represented by a dot .









...
...

Key Modifiers

Vue allows you to add key modifiers for v-on when listening to keyboard events:







It is difficult to remember all keyCodes, so Vue provides aliases for the most commonly used keys:











All key aliases:

Example



Do something