Event handling in Vue3: event binding, event modifiers, custom events

In front-end development, event handling is an important technique that allows us to respond to user interactions and provide a better user experience. As a popular JavaScript framework, Vue3 provides a powerful and flexible event handling mechanism. This article will introduce event processing in Vue3 in detail, including event binding, event modifiers, custom events, etc.

event binding

In Vue3, we can use v-ondirectives or shorthand @for event binding. Here is an example:

<template>
  <div>
    <button @click="onClick">Click me</button>
  </div>
</template>

<script>
export default {
  setup() {
    const onClick = () => {
      console.log('Button clicked')
    }

    return {
      onClick
    }
  }
}
</script>

In the above code, we bind the method to the click event of the button through @clickthe instruction . onClickWhen the button is clicked, onClickthe method is called and prints "Button clicked" to the console. In this way, we have implemented a simple event handling.

In addition to click events, Vue3 also supports various other types of events, such as @input, @submit, @keydownand so on. We can choose the appropriate event type for binding according to the scene.

event modifier

In order to better handle events, Vue3 provides some convenient event modifiers. Event modifiers can be used to change the default event behavior, restrict event trigger conditions, etc. The following are some commonly used event modifiers:

  • .stop: Stop the event from bubbling, that is, stop the propagation of the event in the parent element.
  • .prevent: The default behavior of blocking events, such as page jumps after submitting a form or clicking a link.
  • .capture: Use the event capture mode, that is, listen to events from the outer element instead of the inner element in the bubbling mode.
  • .self: The event handler method is called only when the event fires on the current element itself, excluding child elements.
  • .once: Only trigger the event processing method once, and then unbind the event.

Here's an example that demonstrates how to use event modifiers:

<template>
  <div>
    <button @click.stop="onClick">Click me</button>
    <a href="/" @click.prevent="onLinkClick">Go home</a>
  </div>
</template>

<script>
export default {
  setup() {
    const onClick = () => {
      console.log('Button clicked')
    }

    const onLinkClick = () => {
      console.log('Link clicked')
    }

    return {
      onClick,
      onLinkClick
    }
  }
}
</script>

In the above code, we use .stopa modifier to prevent the button click event from bubbling, and only "Button clicked" will be output in the console. At the same time, we use .preventa modifier to prevent the default behavior of the link click event, the page will not jump, but output "Link clicked".

In addition to the above modifiers, Vue3 also provides many other event modifiers, such as .enter(triggered by the Enter key), .left(triggered by the left arrow key), and so on. Appropriate event modifiers can be selected according to actual needs.

custom event

In development, sometimes we need custom events to achieve communication between components or specific functions. Vue3 provides a mechanism for custom events, allowing us to trigger and listen to custom events in components.

To use custom events in Vue3, we can $emitemit events using methods and $onlisten to events using methods. Here is an example:

<template>
  <div>
    <button @click="onClick">Click me</button>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    const onClick = () => {
      count.value++
      if (count.value === 5) {
        // 触发自定义事件
        emit('reached-max', count.value)
      }
    }

    return {
      onClick
    }
  }
}
</script>

In the above code, when the button is clicked, we increment countthe value of , and emittrigger a reached-maxcustom event named , and countpass the value of , as a parameter, to the event handler.

In the parent component, we can use v-oninstructions or shorthand @to listen to custom events and execute corresponding processing functions. Here is an example:

<template>
  <div>
    <ChildComponent @reached-max="onReachedMax"></ChildComponent>
  </div>
</template>

<script>
export default {
  setup() {
    const onReachedMax = (count) => {
      console.log(`Count reached max: ${count}`)
    }

    return {
      onReachedMax
    }
  }
}
</script>

In the above code, we listened to the custom events @reached-maxsent by the subcomponents , and output the corresponding information in the event handler function.reached-max

Through the mechanism of custom events, we can easily realize the communication and interaction between components, and improve the reusability and maintainability of the code.

Summarize

Vue3 provides a powerful and flexible event handling mechanism that allows us to easily handle user interaction. We can use @instructions for event binding, change event behavior through event modifiers, and use custom events to achieve communication and interaction between components. When we master the event processing function of Vue3, we can better build a front-end application with rich interaction and fast response.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131793963