在vuex中分离数据

时间:2017-09-22 12:43:00

标签: javascript vue.js vuex

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

这些实体通过ID-Arrays连接。

  • Company.employees是一个UserIds数组
  • Employee.workplaces是工作场所ID列表
  • ...

我通过以下两种方式实现了它:

  • 作为一个非常大的商店
  • 包含每个实体的商店模块

第一种方法很简单,但很快变得非常臃肿。第二种方法非常干净,但是当我需要来自2个商店的数据来实现getter时,数据处理很困难(例如:getWorkplacesByCompany)

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

3 个答案:

答案 0 :(得分:3)

模块化肯定更好。它避免了您提到的膨胀,您始终可以通过传递给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>

答案 1 :(得分:1)

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

App
  Blog
    Authors
    Posts
      Tags

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

答案 2 :(得分:1)

我说一个namespaced modules的商店是正确的做法。您仍然可以访问兄弟模块。 因此,在你的getter中,你将rootState作为第三个参数传递,并访问像rootState.Employee.someData这样的同级命名空间。

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

相关问题