[Vuejs]-Multiple instances of Vuex store

0👍

Intuitively, I’d do something like that. Haven’t tested it but it’s probably not ready to use yet.

import UserRepository from '@/repositories/UserRepository';

export default {
  namespaced: true,
  state: {
    loading: false,
    users: [],
  },
  getters: {
    isLoading(state) {
      return state.loading;
    },
    data(state) {
      return state.users;
    },
    usersView() {
      return state.users.view;
    },
    usersOptions() {
      return state.users.options;
    },
    options: (state) => (value = 'id', label = 'name') => state.users.map(
      (user) => ({ value: user[value], label: user[label] }),
    ),
  },
  mutations: {
    SET_LOADING(state, payload) {
      state.loading = payload;
    },
    SET_DATA(state, key, payload) {
      state.users[key] = payload;
    },
  },
  actions: {
    fetch({ commit }, params) {
      return new Promise((resolve, reject) => {
        commit('SET_LOADING', true);
        UserRepository.index(params)
          .then((response) => {
            resolve(response.data.data);
          })
          .catch((error) => {
            reject(error);
          })
          .finally(() => {
            commit('SET_LOADING', false);
          });
      });
    },
    fetchOptions() {
        this.dispatch('fetch', { limit: 0 }).then((users) {            
            commit('SET_DATA', 'options', users);
        })
    },
    fetchView() {
        this.dispatch('fetch', { limit: 15, page: 1 }).then((users) {            
            commit('SET_DATA', 'view', users);
        })
    },
  },
};

0👍

Two stores its never the soultion in my opinion,
try to seperate to 2 modules.
find more here: https://vuex.vuejs.org/guide/modules.html

Leave a comment