gpt4 book ai didi

javascript - 在 vuex 中分离数据

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:22 26 4
gpt4 key购买 nike

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

这些实体通过 ID 数组连接。

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

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

  • 作为一家非常大的商店
  • 每个实体都有商店模块

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

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

最佳答案

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

关于javascript - 在 vuex 中分离数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46365109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com