Vue3 Vue Event Handling Guide

Vue3 Vue Event Handling Guide

1. Basic event handling

Using v-on指令( @ for short), we can listen to DOM events and run handler methods or inline Javascript .

// v-on directive <div v-on:click='handleClick' />

//OR

<div @click='handleClick' />

2. Send custom events to parent components

A common use case in any web framework is to want child components to be able to emit events to their parent components, which is also the principle of two-way data binding.

A common example is sending data from input component to a parent form.

Depending on whether we are using Options API or Composition API , the syntax for emitting events is different.

In Options API , we can simply call this.$emit(eventName, payload ), as shown below:

export default {
  methods: {
    handleUpdate: () => {
      this.$emit('update', 'Hello World')
    }
  }
}


However, Composition API is used differently. You need to use the emit method in the setup method provided by Vue3 .

As long as you import context object, you can call emit with the same arguments as Options API .

export default {
  setup (props, context) {
    const handleUpdate = () => {
      context.emit('update', 'Hello World')
    }

    return { handleUpdate }
  } 
}

Of course, I often use deconstruction in my projects:

export default {
  setup (props, { emit }) {
    const handleUpdate = () => {
      emit('update', 'Hello World')
    }

    return { handleUpdate }
  } 
}

Perfect!

Whether we use Options or Composition API , the way the parent group listens is the same.

<HelloWorld @update='inputUpdated'/>


First, we can $ event訪問傳遞in the template.

If there is a value passed in the component emit method, we can capture it in two different ways, depending on whether we use it inline or using a method.

The first is to use $event in the template to access the passed value.

<HelloWorld @update='inputUpdated($event)'/>


The second method is to use a method to handle the event, and the passed value will be automatically passed to our method as the first parameter.

<HelloWorld @update='inputUpdated'/>

// ...

methods: {
    inputUpdated: (value) => {
      console.log(value) // WORKS TOO
    }
}

Mouse Modifiers

Here is a list of the main DOM mouse events we can capture in the v-on directive:

<div 
  @mousedown='handleEvent'
  @mouseup='handleEvent'
  @click='handleEvent'
  @dblclick='handleEvent'
  @mousemove='handleEvent'
  @mouseover='handleEvent'
  @mousewheel='handleEvent'
  @mouseout='handleEvent'
>
Interact with Me!
</div>


For click events, we can also add mouse event modifiers to restrict which mouse button will trigger our event. There are three: left,right and middle .

<!-- This will only trigger the left mouse button-->
<div @mousedown.left='handleLeftClick'> Left </div>

4. Keyboard Modifiers

There are three DOM keyboard events we can listen to:

<input
   type='text'
   placeholder='Type something'
   @keypress='handleKeyPressed'
   @keydown='handleKeyDown'
   @keyup='handleKeyUp'
/>


Typically, we want to detect these events on a certain key, and there are two ways to do this.

  1. keycodes
  2. Vue has aliases for some keys ( enter , tab , delete , esc , space , up , down , left , right )
<!-- Trigger even when enter is released -->
<input
   type='text'
   placeholder='Type something'
   @keyup.enter='handleEnter'
/>

<!-- OR -->
<input
   type='text'
   placeholder='Type something'
   @keyup.13='handleEnter'
/>

5. System Modifiers

For some projects, we may only want to trigger an event if the user holds down a modifier key. Modifier keys are like Command or Shift.

In Vue, there are four system modifiers .

  1. shift
  2. alt
  3. ctrl
  4. meta ( CMD on mac , Windows鍵on Windows )

This is useful for creating features like custom keyboard shortcuts in your Vue applications.

<!-- Custom shortcut, Yang uses Shift + 8 to create a list -->
<input
   type='text'
   placeholder='Type something'
   @keyup.shift.56='createList'
/>


From the Vue documentation, there is also an exact modifier to ensure that the event is only triggered if the key we specify is pressed and no other keys are pressed.

<!-- Custom shortcuts, only Shift + 8 will create a list when pressed-->
<input
   type='text'
   placeholder='Type something'
   @keyup.shift.56.exact='createList'
/>

6. Event modifiers

As with all DOM events, we can use some modifiers to change the way they operate. Vue has two built-in DOM event modifiers for both stopping propagation and preventing the default action.

<!-- Prevent default behavior -->
<form @submit.prevent>

<!-- Stop bubbling -->
<form @submit.stop='submitForm'>

<!-- Prevent default behavior and bubbling -->
<form @submit.stop.prevent='submitForm'>

<!-- Prevent events from being triggered multiple times -->
<div @close.once='handleClose'> 

There is no way to know in real time what bugs may exist after the code is deployed. In order to solve these bugs afterwards, a lot of time was spent on log debugging. Here I would like to recommend a useful bug monitoring tool, Fundebug.

This is the end of this article about Vue Event Handling Guide of Vue3. For more relevant Vue Event Handling Guide content, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vue's click event anti-shake and throttling processing
  • Detailed explanation of Vue event handling principle and process
  • Detailed explanation of Vue event handling
  • Summary of event handling in Vue.js front-end framework
  • Detailed explanation of Vue event handling and event modifiers
  • Introducing mousewheel events and compatibility processing in Vue
  • Details of event handling in Vue

<<:  Learn more about MySQL indexes

>>:  mySQL server connection, disconnection and cmd operation

Recommend

XHTML Getting Started Tutorial: XHTML Hyperlinks

It is no exaggeration to say that hyperlinks conne...

Detailed explanation of Nginx status monitoring and log analysis

1. Nginx status monitoring Nginx provides a built...

A collection of common uses of HTML meta tags

What is a mata tag The <meta> element provi...

Sharing of SVN service backup operation steps

SVN service backup steps 1. Prepare the source se...

MySQL5.7 master-slave configuration example analysis

MySQL5.7 master-slave configuration implementatio...

MySQL 5.6 zip package installation tutorial detailed

Previously, we all used files with the suffix .ms...

JavaScript realizes magnifying glass special effects

The effect to be achieved: When the mouse is plac...

How to solve the error of connecting to the database when ServerManager starts

Servermanager startup connection database error R...

An article to quickly understand Angular and Ionic life cycle and hook functions

Table of contents Angular accomplish Calling orde...

How to modify the contents of an existing Docker container

1. Docker ps lists containers 2. Docker cp copies...

JavaScript to implement slider verification code

This article shares the specific code of JavaScri...

MySQL database constraints and data table design principles

Table of contents 1. Database constraints 1.1 Int...

JavaScript Timer Details

Table of contents 1. Brief Introduction 2. setInt...

How to build a K8S cluster and install docker under Hyper-V

If you have installed the Win10 system and want t...