Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vue & vuex getter vs passing state via props

Tags:

vue.js

vuex

I have seen many people advising to pass state to components via props rather than accessing the vue state directly inside the component in order to make it more reusable.

However, if I do this consistently this would mean that only the routes root component would communicate with the store and all data needs to be passed through the nested hierarchy in order to get the final component. This seems like it would easily cause a mess:

Dashboard
   Profile
   Billing
      History
      CreditCards
         CreditCard

How would I load data for a users creditcard? In Dashboard and pass it all the way down the tree?

like image 474
Chris Avatar asked Nov 02 '17 07:11

Chris


1 Answers

It will cause a mess, you are correct. This is one of the problems that vuex solves.

So how do you decide whether to pass props or use vuex? When i say use vuex, i mean to access the store data directly from the component that needs it. The trick is to consider each piece of data's relationship to the overall application.

Data that is used repeatedly throughout the page, down many DOM hierarchies, in different pages, etc, is the ideal case in which to use vuex.

On the other hand, some components are so tightly coupled that passing props is the obvious solution. For example, you have a list-container component, whose direct child is the list component, and both of them need the same list data. In this situation, i would pass the list data down to the list component as a prop.


You may be interested in the instance property $attrs

https://v2.vuejs.org/v2/api/#vm-attrs

along with it's sibling option inheritAttrs.

https://v2.vuejs.org/v2/api/#inheritAttrs

Using these 2 in combination allows you to pass props down multiple component levels with less boilerplate code.

like image 167
Eric Guan Avatar answered Nov 15 '22 06:11

Eric Guan