在 vuex 中分离数据

Separating data in vuex

我需要在我的 vuex-store 中存储不同的实体。 例如公司、员工和工作场所...

这些实体由 ID 数组连接。

我用我知道的两种方式实现了它:

第一种方法很简单,但很快就会变得非常臃肿。第二种方法非常干净,但是当我需要来自 2 家商店的数据来满足 getter(例如:getWorkplacesByCompany)

时,数据处理很困难

存储此类数据的首选方式是什么?

如果您按逻辑组织模块和子模块,则可以根据需要数据的位置在商店的每个级别包含 getter。所以你可能有这样的商店和子模块:

App
  Blog
    Authors
    Posts
      Tags

getPostsByAuthor() 的 getter 将在 Blog 模块中,因为它需要来自 AuthorsPosts 的数据,而 getter for getPostsByTag 可以在 Posts 模块中,而 getter for getTagById 可以直接在 Tag 模块中。

我认为 namespaced modules 一家商店是正确的方法。您仍然可以访问同级模块。 因此,在您的 getter 中,您将传递 rootState 作为您的第三个参数并访问像 rootState.Employee.someData.

这样的兄弟命名空间

查看更多https://vuex.vuejs.org/en/api.html

模块化肯定更好。它避免了您提到的膨胀,您始终可以通过传递给 getter 函数的 rootStaterootGetters 选项访问其他模块的数据。

这是一个例子:

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>