Vue3 Event Handling
We can use the v-on directive to listen to DOM events and execute JavaScript code.
v-onThe directive can be abbreviated as@symbol.
Syntax format:
v-on:click="methodName" 或 @click="methodName"
v-on
Try it »
Usually, we need to use a method to call a JavaScript method.
v-on can accept a defined method to call.
v-on
Try it »
In addition to binding directly to a method, you can also use inline JavaScript statements:
v-on
Try it »
Event handlers can contain multiple methods, separated by the comma operator:
v-on
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, through the dot.represented directive suffix, invokes modifiers.
.stop- Stop bubbling.prevent- Prevent default event.capture- Stop capture.self- Only listen to events that trigger on this element.once- Trigger only once.left- Left-click event.right- Right-click event.middle- Middle scroll wheel event
<!-- 阻止单击事件冒泡 --> <a v-on:click.stop="doThis"></a> <!-- 提交事件不再重载页面 --> <form v-on:submit.prevent="onSubmit"></form> <!-- 修饰符可以串联 --> <a v-on:click.stop.prevent="doThat"></a> <!-- 只有修饰符 --> <form v-on:submit.prevent></form> <!-- 添加事件侦听器时使用事件捕获模式 --> <div v-on:click.capture="doThis">...</div> <!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 --> <div v-on:click.self="doThat">...</div> <!-- click 事件只能点击一次,2.1.4版本新增 --> <a v-on:click.once="doThis"></a>
Key Modifiers
Vue allows adding key modifiers to v-on when listening to keyboard events:
<!-- 只有在 keyCode 是 13 时调用 vm.submit() --> <input v-on:keyup.13="submit">
It is difficult to remember all keyCodes, so Vue provides aliases for the most commonly used keys:
<!-- 同上 --> <input v-on:keyup.enter="submit"> <!-- 缩写语法 --> <input @keyup.enter="submit">
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
<input @keyup.alt.67="clear">
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
.exact Modifier
.exactThe modifier allows you to control events triggered by an exact combination of system modifiers.
Example
<button @click.ctrl="onClick">A</button>
<!-- Triggered if and only if Ctrl is pressed -->
<button @click.ctrl.exact="onCtrlClick">A</button>
<!-- Triggered only when no system modifiers are pressed -->
<button @click.exact="onClick">A</button>