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 .
.stop- Stop bubbling.prevent- Prevent default event.capture- Prevent capture.self- Only listen for events triggered on this element.once- Trigger only once.left- Left button event.right- Right button event.middle- Middle wheel event
...
...
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:
.enter.tab.delete(captures the "Delete" and "Backspace" keys).esc.space.up.down.left.right.ctrl.alt.shift.meta
Example
Do something