Emits in Vue 3: A Comprehensive Guide
In Vue 3, emits are a way to pass data from a child component to a parent component. Emits allow you to customize and reuse components by allowing you to specify the data that a component should emit when certain events occur. In this tutorial, we'll take a look at how to use emits in Vue 3 to build dynamic and reusable user interfaces.
To emit an event in Vue 3, you can use the this.$emit
function in the component's methods. The $emit
function takes two arguments: the name of the event, and the data that should be passed with the event.
For example, let's say you have a component called Button
that renders a button element, and you want to allow the parent component to handle the click event:
<template>
<button @click="handleClick">{{ label }}</button>
</template>
<script>
export default {
props: {
label: {
type: String,
default: 'Button',
},
},
methods: {
handleClick() {
this.$emit('click');
},
},
};
</script>
In this example, the Button
component is defined in the export default
object, and the props
option is used to define a label
prop that allows you to customize the label of the button. The template
contains a button element that displays the label
prop and has a click
event listener that calls the handleClick
method. The handleClick
method uses the $emit
function to emit a click
event.
To use the Button
component in your application, you can use the <Button>
element in a template and specify an event listener using the @
syntax:
<template>
<Button @click="handleClick"></Button>
</template>
<script>
import Button from './Button.vue';
export default {
components: {
Button,
},
methods: {
handleClick() {
console.log('Button clicked');
},
},
};
</script>
In this example, the Button
component is imported and registered in the components
option, and the Button
element is used in the template to render the Button
component. The @click
attribute is used to specify an event listener that listens for the click
event emitted by the Button
component. When the click
event is emitted, the handleClick
method is called, which logs a message to the console.
By using emits, you can customize and reuse components in different parts of your application. Whether you're building a simple form or a complex single-page application, emits are a key feature for building dynamic and reusable UIs with Vue 3.