乐闻世界logo
搜索文章和话题

What are the event modifiers provided by vue?

1个答案

1

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:

  1. .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>
  1. .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>
  1. .capture - Uses the capture phase, where events on internal elements trigger before external elements.
html
<div @click.capture="doThis">Click me</div>
  1. .self - Handles the event only when triggered directly on the element itself (not on child elements).
html
<div @click.self="doThis">Click me</div>
  1. .once - The event triggers only once.
html
<button @click.once="doThis">Click me</button>
  1. .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 回复

你的答案