DEV Community

Andrei Gatej
Andrei Gatej

Posted on

Vue.js: Sharing data between components with Vue.observable()

While I was working on a project, I found myself in a tricky situation.(You can find the project here)

I needed to find a way to share data between two components, but the data was to small to be stored in Vuex and passing it through the components would've cluttered things up.

After some research, I've found exactly what I was looking for: Vue.observable().

To put it simple, it makes an object reactive.
This can be used to our advantage: if the object that is shared between 2 components is modified by the component A, the changes will be reflected in component B(and vice versa).

A real use case

This is how a Dashboard component would look like:

As you can notice, the Dashboard consists of multiple cards: History, VAT, Documents.

Now, I'd kindly ask you to focus your attention on the History card.
The behaviour I expect is that every time the user clicks on a row, a modal will be opened and will show the proper information about that row.

My approach to this problem is to create two separate components, one which will display the rows and one which will contain the modal.

Here's the idea translated into code:

Now the following question arises: How does the HistoryModal component know when a row has been clicked?

Well, let's see how Vue.observable can help us.

First of all, we set the reactive object in src/observables/history.js

In src/views/dashboard/History.vue we pass the reactive object to data property in order to use it in the template and also modify it.

Any changes from History.vue will be reflected in src/views/dashboard/HistoryModal.vue. Everything works as expected!

Conclusion

I hope this article was able to shed a light on some similar issues you might have faced or simply to illustrate how powerful Vue.js is.

Thank you for reading!

Top comments (4)

Collapse
 
cecilphillip profile image
Cecil L. Phillip šŸ‡¦šŸ‡¬

Nice post. I've been looking for a simple examples/use case for Vue.observable()
Thanks for writing this up

Collapse
 
anduser96 profile image
Andrei Gatej

Thanks! Iā€™m really glad you found this useful!

Collapse
 
danielelkington profile image
Daniel Elkington

Very interesting solution - thanks for sharing!

Collapse
 
anduser96 profile image
Andrei Gatej

Thanks for the feedback!