Search code examples
vue.jsvuexstorevuex-modules

Vuex: Is it a bad practice for two components to use same store module?


Let's suppose you create a new Vue component BComponent, with a new store module BModule, and you need to use some state logic that you already have done in AModule used in AComponent (a request to an API endpoint).

Is it a bad practice to use the logic you already have? What are the problems that may encounter here? May it affect the AComponent somehow?

Thanks in advance!


Solution

  • I think this depends on context.

    Generally, no, it's not a bad practice. Say you have a "Cart module" and "Listing component" and "Cart component", it is totally acceptable to do that.

    Your store and components should be agnostic from each other so it remains reusable in that:

    • Your store shouldn't care what component uses it. It is your client-side "database".
    • Your components shouldn't care what else uses the store it uses.

    The nature of question is similar to database structuring or class modeling in that do you, for example:

    • split "Teacher" and "Student" entity and repeating same properties/methods
    • have a parent "Person" entity which "Teacher" and "Student" can extends (inheritance)
    • compose objects (composition)

    In some cases, "Teacher" and "Student" might have same stuff in early stages but later on ends up having totally different stuff.

    I think usually Composition is preferred over Inheritance because it can somehow do the same thing without being restricted to the parent and more.

    You can do something like:

    const Teacher = addTeachingSkills(createPerson())
    const Student = addLearningSkills(createPerson())