Sharing data in vuex

I need to store different objects in my vuex repository. For example, companies, employees and jobs ...

These objects are associated with ID arrays.

  • Company.employees is an array of UserIds
  • Employee.workplaces - list of workplace identifiers
  • ...

I implemented this in both directions, I know:

  • like one very big store
  • with storage modules for each object

The first approach is simple, but quickly becomes very bloated. The second approach is very clean, but data processing is difficult when I need data from 2 stores to execute getter (for example: getWorkplacesByCompany)

What is the preferred way to store such data?

+6
source share
3 answers

. , , rootState rootGetters, getter.

:

const employees = {
  state: {
    employees: [
      { id: 1, name: 'Jeff' },
      { id: 2, name: 'Joe' },
      { id: 3, name: 'Jimmy' },
      { id: 4, name: 'Jake' },
      { id: 5, name: 'Jill' },
    ]
  },
}

const companies = {
  state: {
    companies: [
      { id: 1, name: 'Foo Co.', employeeIDs: [ 1, 4, 5 ] },
      { id: 2, name: 'Bar Co.', employeeIDs: [ 2, 3, 5 ] },
    ]
  },
  getters: {
    getCompanyEmployees(state, getters, rootState, rootGetters) {
      return (companyID) => {
        let company = state.companies.find((c) => c.id = companyID);        
        return rootState.employees.employees.filter((e) => {
          return company.employeeIDs.indexOf(e.id) >= 0;
        })
      }
    }
  }
}

const store = new Vuex.Store({
  modules: { employees, companies }
})

new Vue({
  el: '#app',
  store,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.4.0/vuex.min.js"></script>

<div id="app">
  {{ $store.getters.getCompanyEmployees(1) }}
</div>
Hide result
+2

, , . , :

App
  Blog
    Authors
    Posts
      Tags

getPostsByAuthor() Blog, Authors Posts, getter getPostsByTag Posts, getter getTagById Tag.

+1

I would say that one store with namespaced modules is the right approach. You still have access to the modules for sisters. Thus, in your recipient, you will pass rootStateas the third argument and gain access to the sisters namespace, for example rootState.Employee.someData.

Read more https://vuex.vuejs.org/en/api.html

+1
source

All Articles