Vue 3 Event Handling
We can use the v-on directive to listen for DOM events and thereby execute JavaScript code.
v-on The directive can be abbreviated as the @ symbol.
Syntax format:
v-on:click="methodName"
或
@click="methodName"
v-on
<
div
id
=
"
app
"
<button@click=">counter += 1
"
Increment by 1
button
<
p
This button has been clicked {{ counter }} times.
p
div
<
script
const app = { data() { return { counter: 0 } } } Vue.createApp(app).mount('#app')
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@click="greet">Click me
button
div
<
script
const app = { data() { return { name: 'Runoob' } }, methods: { greet(event) { // methods Inside, the this points to the current active instance alert('Hello ' + this.name + '!') // event is the native DOM event if (event) { alert(event.target.tagName) } } } } Vue.createApp(app).mount('#app')
script
Try it »
Besides directly binding to a method, you can also use inline JavaScript statements:
v-on
<div id="app">
<button@click="say('hi')">Say hi
button
<button@click="say('what')">Say what
button
div
<
script
const app = { data() { }, methods: { say(message) { alert(message) } } } Vue.createApp(app).mount('#app')
script
Try it »
An event handler can contain multiple methods, separated by the comma operator:
v-on
<div id="app">
<button@click=">one($event), two($event)
"
Click me
button
div
<
script
const app = { data() { }, methods: { one(event) { alert("First event handler logic...") }, two(event) { alert("Second event handler logic...") } } } Vue.createApp(app).mount('#app')
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
System modifier keys:
.ctrl.alt.shift.meta
Mouse button modifiers:
.left.right.middle
Example
Do something
.exact modifier
The .exact modifier allows you to control events triggered by an exact combination of system modifiers.
Example
A
A
A