Vue Emit Data To Parent

Posted on  by admin
Conclusion

Subscribe to my newsletter and never missmy upcoming articles. Ever wondered if you could pass data from your child component to its Parent component in Vue?

Or you didn't understand how it worked? If yes, then this article is meant for you. We'll be building a mini Vue app that demonstrates how to pass data from child to parent component using the emit event.

Basic knowledge about Vue. Vue CLI installed on your computer.You can install Vue CLI with the following command using Yarn:. We will be using the Vue CLI tool to bootstrap a new Vue project. First, we create a new project using the create command:. Move your down arrow key to default Vue 2 option and press enter. Next, change directory into the project folder with this command:.

Start your project with the command:. You should see your app running on localhost:8080 after running the yarn serve command. In our App, we are going to have two components, which are the App.vue and we'll create a Child.vue component.

The child component will have a text field which will take in user input and display that information in the App component.

The app we'll be building is as simple as it looks.

The part with the red border around it is the App component, while the section with the blue border is the Child component.

Your App.vue component should look like this. I've added some global styles, nothing complex. Then in your Child.vue component, you should have the following code:. In the Child.vue component, you'll notice a method sendData attached to the keyup.enter and @click.prevent event handlers.

keyup.enter calls the sendData method when the enter key is pressed.while click.prevent stops the default behavior of forms. This is to trigger the function which contains the emit event to run when we hit the enter key or click on the button.

Getting Started:

Goals:

Then we create a method in the Child.vue component with the name sendData 👇👇. this.$emit propagates a custom event and by default propagates an event, it can also propagate data but in this scenario we are sending both which is why it takes two values.The two values being: The name of the event you want to emit.

In our case "inputData" and it's data; "this.input".

In more complex cases we might need to send more than one data value which the emit method allows us room to do.