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

Vue 3 Event Handling

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 .









...
...

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:

System modifier keys:

Mouse button modifiers:

Example

Do something

.exact modifier

The .exact modifier allows you to control events triggered by an exact combination of system modifiers.

Example