How to use @Props, @Emit in Vue, Vuetify and Typescript
In this post am going to share with you how @prop and @emit works in Vue. This content is based on self-experience. And the term definitions where simplified by my colleague.
Let’s get started.
What is a prop?
A prop is the value received in the child component from the parent component. When you use @Prop that means a child component is receiving values from the parent component.
What is an Emit?
When the child component wants to send data to the parent component it uses @Emit and the parent component receives what has been emitted through a function.
In this explanation am using a dialog without activator from Vuetify documentation
Step by step ways of using a @Prop and an @Emit
We need to have two components created. One will name Child.vue and another Parent.vue
In our Child.vue component our first code should look like this
Step 1: Import Prop and Emit
If you are using typescript, it is important that you import Prop and Emit too
Step 2: create a Prop called display
Step 3: Create a computed Method called showDislay that returns a Prop value above if you intend on mutating the value of display.
Step 4: Create two Emits that will help us pass data to the parent.
First Emit will help in closing the dialog and Second Emit will help in opening the dialog.
Step 5: After you are done creating Emits, they need to be passed in the buttons.
The complete Child.vue file should look like below.
Parent component
Step 1: the code in our Parent.vue should look like below
Step 2: Here we are importing a Watch learn more on Vue documentation
Step 3: Here we import the Child.vue component in the parent.
Am not going to talk about the modals because I assume you are already familiar with them, if you want to learn more about them visit the Vuetify documentation above.
Step 4: We initialize a value that will help the parent send data to the child
In your modal tag, bind a prop value display from the child component to dialog, this is how a parent component will send data to the child component.
Step 5: We need to create functions
This will show a dialog once an Emit is sent from the child component
Parent doing something as the reaction of the child
After creating the close and the save function, we need to connect them to the child component Emitted values like below
This will enable the parent component, to receive data from the child component.
Awesome, hopefully this post helps you understand how Props and Emits work. If it works for you, a clap will be appreciated. Happy coding.