Table of contents
No headings in the article.
Photo by Liane Metzler on Unsplash
Hi dear developer,You have just started learning vuejs and you want a quick and simple way to communicate between parent and child components so you are in the right place. In this short tutorial I'll walk you through how to:
Pass data from parent to child component:
To get started I have created vue app( you can find it here: codesandbox.io/s/communication-between-pare..). For now the project is empty: Now let's create two Parent and Child components in components folder and then import Parent component in App.vue as shown bellow: Cool! let's now create an input field, bind it to a variable called "messageFromParent" and pass it to Child component in a variable called "message" (ofcourse you need to import Child component): In order for Child component to be able to use the "message" variable, we need to pass it in an array called props and then use it as usual: Now if you write anything in the input field, it gets displayed in h1 tag present in Child component:Pass data from child to parent component:
Congrats, you just learned how to pass data from Parent to Child what about the other way around?To achieve the above goal, we need two things to be present in Parent component: a variable called "messageFromChild" and a method "getMessageFromChild" that sets "messageFromChild" to data coming from Child component. Second we need to pass "getMessageFromChild" method to Child component same as we did previously in part one: In Child component we create an input field, bind it to a variable called "messageFromChild" and handle any keypress by calling "getMessage" that takes "messageFromChild" as argument. Finally add "getMessage" to props: Hope you enjoyed it, if so please give it thumps up,
Also if you have any question, suggestion or improvement leave it in the comment and I'll get back to you
My social media accounts, feel free to connect to me on: