Event modifiers in Vue.js are special directives that specify how the compiler processes DOM events. Here are some common event modifiers provided by Vue:
- .stop - Calls
event.stopPropagation()to prevent event propagation. For example, in nested elements, this modifier prevents click events from bubbling up to parent elements.
html<button @click.stop="doThis">Click me</button>
- .prevent - Calls
event.preventDefault()to prevent the default behavior of the event. Often used for validation before form submission, preventing the form from being submitted.
html<form @submit.prevent="onSubmit">Submit</form>
- .capture - Uses the capture phase, where events on internal elements trigger before external elements.
html<div @click.capture="doThis">Click me</div>
- .self - Handles the event only when triggered directly on the element itself (not on child elements).
html<div @click.self="doThis">Click me</div>
- .once - The event triggers only once.
html<button @click.once="doThis">Click me</button>
- .passive - Used for performance optimization, indicating that the event handler does not call
preventDefault().
html<div @scroll.passive="onScroll">Content</div>
These modifiers can be used individually or combined to achieve finer-grained event handling. For example, to create a click event handler that triggers only once and does not bubble, you can write:
html<button @click.stop.once="doThis">Click me</button>
Using these modifiers makes event handling logic clearer and more concise, enhancing code readability and maintainability.
2024年7月22日 18:24 回复