整個系列寫得太嚴肅了,這次在標題上小小的中二一下。
vuex 的 getters 用來展現欲望,展現想要使用資料的樣子。這個道理是基於 ADT 的設計。Web API 的 GET api 也是一樣的道理,所以 GET 通常會帶很多 query。也正因為如此,所以 facebook 後來推出了 GraphQL 我想也是為了滿足人類各式各樣的欲望,讓 GET 資料的方式更加彈性。
@/store/user/index.js
做在 mutation 存在 state
import actions from './actions';
export default {
//...
state: {
leader_users: [],
active_users: [],
},
mutation: {
leaderUsers (state, users) {
const leader_id_list = [...users.reduce((leaders, user) => {
leaders.add(user.department.leader_id)
return leaders;
}, new Set())];
state.leader_users = users.filter(user => leader_id_list.includes(user.id))
},
activeUsers (state, users) {
state.active_users = users.filter(user => user.is_active)
}
},
getters: {
leaderUsers(state) {
return state.leader_users;
},
activeUsers(state) {
return state.active_users;
}
}
}
缺點
@/store/user/index.js
做在 getters
import actions from './actions';
export default new Vuex.Store({
//...
getters: {
leaderUsers (state) {
const leader_id_list = [...state.list.reduce((leaders, user) => {
leaders.add(user.department.leader_id)
return leaders;
}, new Set())];
return state.list.filter(user => leader_id_list.includes(user.id))
},
activeUsers (state) {
return state.list
.filter(user => user.is_active)
}
}
})
個人偏愛這一種安排方式
優點
缺點
不過這就是本質性問題!只能移動、隱藏,無法消滅
部門主管,屬於 department 的 module
@/store/department/index.js
做在 getters
import actions from './actions';
export default new Vuex.Store({
//...
getters: {
leaders (state, getters) {
const leader_id_list = state.list.map(department => department.leader_id);
return getters.users.filter(user => leader_id_list.includes(user.id))
},
// ...
}
})