Provide/inject or Vuex?
Asked Answered
M

1

6

I have a list of cars. Each item of that list has all the information about some of the cars. Also each item is a parent component to many other components - image, price, characteristics, etc - all that info is in separate components. The information about all those cars is stored in Vuex. Now I am trying to think of a better way to pass that information to each of the list items.

  1. Pass all the necessary data about another car to the parent component. And then provide it to the child components.
  2. Each child component gets the necessary information from Vuex directly.
Main answered 20/11, 2021 at 11:25 Comment(6)
The whole point of Vuex is to provide globally accessible state. If you are already using Vuex, then there is no point trying to pass data between components another way.Christlike
Provide/inject is only needed alongside Vuex if you have component-specific data that needs to be provided to nested components.Kopple
@match, yes! But the thing is every child component of the list item should know the id of the car to display the right information. So I should provide the car id from the parent to all it's children anyway so they can get the information from Vuex by that id.Main
Yes - I would pass the id each child element is to display in as a prop, then let the child look up the data itself, rather than passing the whole data object as a prop.Christlike
@EstusFlask every child component of the list item should know the id of the car to display the right information. So I should provide the car id from the parent to all it's children anyway so they can get the information from Vuex by that id. Is provide the whole data from parent to it's children a good solution in this case?Main
Most times this is solved through props, where you can provide a subset of data. Provide/inject or Vuex is needed for deeply nested data to avoid passthrough props at many levels. If you're able to provide id to a component, you're likely able to provide the rest of data. Also accessing data in Vuex doesn't mean that you need to provide all data. It can be a needed subset via a getter.Kopple
R
6

Provide-inject is mainly used to pass data to nested components.

Vuex on the other hand, keeps the app state shared.

You need to ask yourself whether the data you need in your component is coming from a parent-parent component or the data is used in many components in different parts of the app. If you need the first, then go with the provide-inject, otherwise, pick Vuex.

Both approaches are prone to be badly implemented and potentially impact negatively on your app development and maintainability, so be very careful and learn the basics in-depth ;)

Rydder answered 12/4, 2022 at 11:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.