Zach Smith
Zach Smith

Reputation: 45

How to re-use Vuex state fields/actions/mutations between modules?

So I'm unaware of a Vuex best practice for doing something like this - if there is, please feel free to leave a link so I can do further research.

What I need is to be able to re-use a set of Vuex fields/actions/mutations between 2 (or possibly more) Vuex modules. I have an application whose Vuex modules' state is closely coupled to their API call schemas.

Perhaps the "best practice" solution is to create a separate Vuex module with the fields/actions/mutations I need, but the new module's fields would have to be added to the other modules' state for API calls anyway, which makes the separate module idea seem like more trouble than it's worth.

Here's a basic example:

// TodosModule.js

export default {
  state: {
    todos: [],
  },

  actions: {
    async saveTodos({ state }) {
      await this.Api.saveTodos(state.todos);
    },

    setTodos({ commit }, newTodos) {
      commit('SET_TODOS', newTodos);
    },
  },

  mutations: {
    SET_TODOS(state, newTodos) {
      Vue.set(state, 'todos', newTodos);
    },
  },
};
// HeroesModule.js

export default {
  state: {
    heroes: [],
  },

  actions: {
    async saveHeroes({ state }) {
      await this.Api.saveHeroes(state.heroes);
    },

    setHeroes({ commit }, newHeroes) {
      commit('SET_HEROES', newHeroes);
    },
  },

  mutations: {
    SET_HEROES(state, newHeroes) {
      Vue.set(state, 'heroes', newHeroes);
    },
  },
};

I need to be able to add a set of fields to both modules because these fields are needed in their API calls. What that might look like is:

// TodosModule.js

export default {
  state: {
    todos: [],
    
    // shared fields are declared somewhere up here
  },

  ...

  actions: {
    async saveTodos({ state }) {
      await this.Api.saveTodos({
        todos: state.todos,
        sharedFieldOne: state.sharedFieldOne,
        sharedFieldTwo: state.sharedFieldTwo,
      });
    },
  },
};

What is the best practice, or DRY-est way to do so?

EDIT: I should clarify - I only want the fields placed into the modules - I don't want the fields to share the same value in between modules. Meaning, I don't want the value to change in one module because it changed in another. They should be their own individual references.

There is this part of the Vuex docs: https://vuex.vuejs.org/guide/modules.html#module-reuse

But that seems to be referring to the kind of cross-pollination I don't want. It seems the one value is shared between all of the instances of the field.

Upvotes: 0

Views: 57

Answers (0)

Related Questions