How Vue data flow works — A practical example

DavidMM
DavidMM
May 6, 2019 · 7 min read
Image for post
Image for post

When I started using Vue I fell in love with it. Easier than Angular, the front-end framework I was using, and a lot of fun to use. But as I was learning, I was overwhelmed about the options of Vue data flow. How can I pass data to a sibling component? How can I pass down data to a children component? What about another component where they have no relationship?

Let’s analyze all the ways you can pass around data in Vue, and which one should you use and when.

If you need a less technical, more conceptual explanation, here’s one. Read it before keep reading if you are a total beginner in Vue

Our options

  • In the same component
  • Props/$emit
  • EventBus
  • Vuex store

And all of 4 are useful. To fix something sometimes you need a hammer, sometimes duck tape. There is no “universal tool” you can buy and discard every other tool. You need all of them an learn their place and way to use. Let’s learn them.

Our code

Nothing fancy, just a website with two parts: One listing items to buy, their prices and the amount available, and the other one lists which items you have bought, how many and the total sum.

Image for post
Image for post
Yes. The design is simplistic. This is the best I can do.

As you can see, there is a menu with four links: once to each option I mentioned before.

In each case you can click the ‘+’ sign to add a n item to the shopping cart, removing it from the store. And a ‘-’ to do the opposite. And in each case, the ‘total’ of your cart would be re-calculated.

You can download it here: https://github.com/david1707/shopping-cart

Sharing data between the same component

The code is pretty clear. Items and ShoppingCart are arrays containing the data, we have a computed variable, totalShopping that calculates how much you are going to spend, and an addItem and removeItem methods that do what their names say.

Even if you are a new Javascript programmer, can understand everything that happens there.

The code is within the same component and it’s easy to understand.

Props and $emit

Image for post
Image for post

But now things get complicated. What happens when we have a 4-level component web application? What when we have a container component with 3 siblings components?

In this example, we have a parent component, the container component, and two child component: An Item Side component and a Total Side component:

Image for post
Image for post

Until now, the methods and data were in the same component. Now they are separated and have to interact between them. When we click on the ‘+’ button, we have to remove one item from that type on the Item side component, but also add one at the Total side component. But also pass the price.

Sadly, props and $emit only use a parent/child relationship: You can’t pass information directly to another component. Props pass data to a children component, $emit sends data to its parent.

So, if we want to pass data from the Item component to the Total component, we need to use $emit to send the data up to the parent Container from the Item, then down to the Total component via props. Let’s see the relevant code:

ItemSideComponent.vue:

Here, the addItem method takes the name and price, and “emits” a signal with the ‘addItem’ flag: Any component listening to this flag will notice.

Let’s see the parent component, Container, that should be listening to this:

As you can see, we are listening to the ‘addItem’ signal we emitted at the props-item-side element, and as soon we receive anything, we’ll call the method addItem that will change the item object. Now we have to pass it down to the props-total-side. For that, we need to use props.

<props-total-side :newItem=”item” /> sends down the item object as newItem, and it will be received as prop:

And now we do the second part of the method: Adding it to the shoppingCartarray.

As you can see, the method contains the same code, but it is split between 3 components. We have to do this as we are affecting different components.

Now you may think: What if we have to pass some data to a component inside a component inside a component inside a component inside…? Do I have to use props and/or emits on each one?

The answer is yes. Unless we use an EventBus.

EventBus

Image for post
Image for post

If our project is complex, with a lot of components interacting with data, you’ll go crazy. Imagine a small project with 12 components, passing up and down data. It should be a better way to do this, right?

Luckily, it is.

EventBus has the same principle of props and $emit, but as a super-parent.

Every single component is children of the Eventbus, so no matter how far away are two components sharing data: They’ll always have the EventBus as parent component.

So now, we just need to interact between the component sending the data and the one receiving the data. EventBus just acts as “middleman”.

Let’s see the code. First, we create a root level file called event-bus.js:

Yep, just like that. Now EventBus can be imported and we can use it. Here it is our ItemSideComponent:

Just similar to using props and $emit, but without using any other component. Now, our TotalSideComponent:

Now, as you see, we import the EventBus and we start listening to the ‘addItem’ flag, as shown on ‘created’. As soon we get a signal, we trigger the addItem method. Way simpler.

Vuex

Image for post
Image for post

EventBus was an improvement, but we still have to send signals to an EventBus, listening to them and, if our project is big enough, will be a bit hard to chase where is everything. And we can even have duplicated code if we use methods in two or more components.

Vuex fixes that.

Vuex is a state management library that serves as a centralized store, being the single source of truth of your project.

Ok. Let me explain.

Remember how we passed up and down the data, have a few methods, etc? Now imagine the same with a project of 6 components. Or 20. It would be madness, right?

Imagine that you create a store where you can add items, then pass said items to the buying page, then the confirm, then…

Vuex acts as a single source of truth with its own state. Every component pulls the data from Vuex state. If we need some data, we pull it from Vuex state. Not from other components but just the state. As every component information is fetched from Vuex state, there is no conflict.

Let’s see the Vuex store:

Cool, now we have all the logic in one single file! This way when we have to change anything, we just need to go to the store.js file to modify it. No more chasing code in components!

Also, this ensures we follow the “Don’t Repeat Yourself” directive.

Now, every component just need access to each method and state values.

ItemSideComponent:

TotalSideComponent:

Way less complex. And if you need to create more components that use some functionality, you just need to import the method(s) and that’s it.

Of course, this adds a bit of complexity as you have to set Vuex, the store, and on big applications you need to split your store.js into modules (auth.module.js, user.module.js, etc), but it is worth as will save you a lot of pain.

Cool…Which one I should use then?

Every way has its own place, you just need to use your own judgement. But let me help you:

  • Simple component: Used only to manipulate the data already existing in the component.
  • Props and $emit. Used to pass down/up data between parent/children components. You can manage to pass data between components on different levels, but it is unnecessarily hard. Only use it when you are using shared components as custom buttons and the like to pass down as props data (For example, when you import components).
  • EventBus. Used to pass data between components. Distance doesn’t matter here as you are using an EventBus component that acts as middle-man of each component. Use it to pass data between components with two or more degrees of separation or to trigger functions.
  • Vuex. My default choice unless what I’m doing is super simple. A single source of truth is great and makes impossible to lose data. Also, the re-usability of methods is great.

I cannot stress this: Every option has its uses, learn all of them and apply the one that suits best to your project.

More information:

Reach to me on Twitter

My Youtube tutorial videos

Contact me: DavidMM1707@gmail.com

Originally published at https://letslearnabout.net on May 6, 2019.

Vue.js Developers

Helping web professionals up their skill and knowledge of…

DavidMM

Written by

DavidMM

Valencian Full Stack | Python | Django | DRF | Javascript | Vue | Flutter | Creator of http://letslearnabout.net/

Vue.js Developers

Helping web professionals up their skill and knowledge of Vue.js

DavidMM

Written by

DavidMM

Valencian Full Stack | Python | Django | DRF | Javascript | Vue | Flutter | Creator of http://letslearnabout.net/

Vue.js Developers

Helping web professionals up their skill and knowledge of Vue.js

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store