DEV Community

Cover image for Sharing Data Between Components in Vue.js

Sharing Data Between Components in Vue.js

Alex Mourer on November 29, 2018

In this tutorial, we'll explore generating data in one component, and passing it to another in Vue.js. TL;DR Here is an example of a working Code...
Collapse
 
giorgosk profile image
Giorgos Kontopoulos 👀 • Edited

Nice writeup Alex, thanks for sharing.

I have forked your example and have made it work with a Global EventBus using EventBus.$emit and EventBus.$on. This way any Component can choose to listen to this event which makes for a cleaner solution I think.

You can see my changes here codesandbox.io/s/mq2yl9lw8p

Do you know why would someone choose one over the other method ?

Collapse
 
alexmourer profile image
Alex Mourer

Hey George! Your fork looks great, thanks for providing this.

I did look into using EventBus.$emit for the example, but I was trying to keep the components as modular as possible. While creating the file event-bus.js is not a huge lift, it is an additional item the component is dependent on.

I think your solution is 100% acceptable.

Collapse
 
franciscosuca profile image
franciscosuca

This was really helpful for a beginner like me, thanks!

Collapse
 
ronokdev profile image
Farhan fuad Ronok

Very good post!!
Keep it up. 👍👍👍👍👍👍

Collapse
 
dysiode profile image
Patrick Kennedy

This approach to watching the property is very unique. Is there a usecase where it would be preferable to storing the message list in the parent or emitting events from the parent and listening in the child?

Collapse
 
alexmourer profile image
Alex Mourer

Hey Patrick, you are correct. The watch property section in the example is somewhat unique. I wanted this component to be able to accept a string from any source and then create an array from that inside the component.

I would be interested in seeing an example of what you are suggesting. If you have time, feel free to fork the codesandbox example.

Collapse
 
fperniavp profile image
Fabián Pernía

Clear and simple. Thanks!

Collapse
 
kimmydoray profile image
Kimmydoray

Nice Sir Alex, what a great tutorial thanks. :) <3

Collapse
 
franciscosuca profile image
franciscosuca

Great explanation! thank for your content!