The process of event binding in vue

The binding of events in Vue is divided into two situations: native DOM events and component events.

Native DOM events

It refers to the event that uses v-on or @ directive in the template to bind the element, such as

<button @click="handler">click me</button>

Binding of this kind of event is achieved through the following steps:

  • During the template compilation phase , Vue will parse the v-on/@ directive and generate the corresponding AST node, which contains information about the event name and event processing function.
  • In the render function generation phase , Vue will generate the code corresponding to the v-on/@ instruction based on the AST node, such as on: {click: handler}, and use it as an attribute of the VNode.
  • In the phase of creating a real DOM node , Vue will call the createElm function, which will call the invokeCreateHooks function to traverse and execute platform-related hook functions, including the updateDOMListeners function, which is responsible for comparing the event listeners of the old and new VNode, and adding or removing corresponding events. For binding, use the native addEventListener and removeEventListener methods.

Component events

Refers to the event triggered by using the $emit method in the component, such as this.\$emit('submit', payload).

Binding of this kind of event is achieved through the following steps:

  • In the component options , you can declare the events to be triggered through the emits attribute or the defineEmits function. This can be used as a document to record the usage of the component in the code. It can also type-check the parameters of the event to improve the maintainability and safety of the code. Robustness.
  • In the component's template , you can use the v-on or @ directive to listen for component events, such as
     <MyComponent @submit="callback" />
    
    This will pass the event listener to the component as a property of the VNode.
  • In an instance of a component , you can use the $emit method to trigger component events, such as this.\$emit('submit', payload). This method will trigger a custom event on the current component instance and pass it some parameters.
  • During the rendering process of the component , Vue will call the updateComponentListeners function, which will traverse the event listeners of the component VNode and add them to the _events attribute of the component instance. This attribute is a mapping table of event names and event handling functions.
  • In the $emit method of the component , Vue will look for the corresponding event processing function in the _events attribute based on the event name. If it exists, execute them in sequence and pass the event parameters.

Guess you like

Origin blog.csdn.net/olderandyanger/article/details/135248882