This article brings you relevant knowledge about vue, which mainly introduces related issues about basic event processing. Vue event processing is a necessary aspect of every Vue project. It is used to capture user input, share data, and many other creative ways. Let’s take a look at it together, I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, vue.js tutorial】
Vue event processing is A necessary aspect of every Vue project. It is used to capture user input, share data, and many other creative ways.
In this article, I'll cover the basics and provide some code examples for handling events.
Using the v-on directive (@ for short) we can listen to DOM events and run handler methods or inline Javascript:
<div v-on:click='handleClick' /> <!-- 相当于 --> <div @click='handleClick' />
We will cover Some of the more common events you might want to capture, click here for a complete list of DOM events.
A common use case in any web framework is to want a child component to be able to emit events to its parent component. This will allow two-way data binding.
An example of this is sending data from an input component to a parent form.
The syntax for emitting events is different depending on whether we are using the Options API or the Composition API.
In the Options API, we can simply call this.$emit(eventName, payload):
export default { methods: { handleUpdate() { this.$emit('update', 'Hello World') } } }
However, the Composition API does not have this. Instead, we can access the emit method directly using the Vue3 setup method.
The second parameter of the setup method is the context variable, which contains three attributes: attrs, slot and emit.
As long as the context object is imported, emit can be called with the same parameters as the Options API.
export default { setup (props, context) { const handleUpdate = () => { context.emit('update', 'Hello World') } return { handleUpdate } } }
One way to clean up your code is to use object destructuring to import emit directly. It looks like this.
export default { setup (props, { emit }) { const handleUpdate = () => { emit('update', 'Hello World') } return { handleUpdate } } }
Whether we use the Options API or the Composition API, our parent components listen to custom events in the same way.
<HelloWorld @update='inputUpdated'/>
If the method we emit is also passed a value, we can capture it in two different ways - depending on whether we work inline or use another method.
First, we can use the passed $event value in the template.
<HelloWorld @update='inputUpdated($event)'/>
Secondly, if we use a method to handle the event, the value passed will be automatically passed to our method as the first parameter.