Tho*_*mas 6 javascript vue.js vuex
我需要在我的vuex商店中存储不同的实体.例如公司,员工和工作场所......
这些实体通过ID-Arrays连接.
我以两种方式实现了它:
第一种方法很简单但很快变得非常臃肿.第二种方法非常干净,但是当我需要来自2个商店的数据来实现getter时,数据处理很困难(例如:getWorkplacesByCompany)
存储此类数据的首选方式是什么?
模块化肯定更好。它避免了您提到的膨胀,并且您始终可以通过传递给 getter 函数的rootState
或选项来访问其他模块的数据。rootGetters
这是一个例子:
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,
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
325 次 |
最近记录: |