Created
September 18, 2019 07:39
-
-
Save web-crab/07681fd92c82cd0509b063a2cd95e03c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from 'vue' | |
export default (api) => ({ | |
namespaced: true, | |
state: { | |
list: [] | |
}, | |
getters: { | |
idxMap: state => state.list.reduce((map, { id }, i) => { | |
map[id] = i | |
return map | |
}, {}), | |
byId: (state, getters) => id => state.list[getters.idxMap[id]] | |
}, | |
actions: { | |
async all ({ state }) { | |
if (state.list.length) { | |
return state.list | |
} else { | |
const list = await api.get() | |
state.list = list | |
return list | |
} | |
}, | |
async one ({ getters }, id) { | |
return getters.byId(id) || api.get(id) | |
}, | |
async add ({ state }, item) { | |
const newItem = await api.add(item) | |
state.list.push(newItem) | |
return newItem | |
}, | |
async set ({ state, getters }, item) { | |
const i = getters.idxMap[item.id] | |
const newItem = await api.set(item) | |
Vue.set(state.list, i, newItem) | |
return newItem | |
}, | |
async del ({ state, getters }, id) { | |
const i = getters.idxMap[id] | |
await api.del(id) | |
Vue.delete(state.list, i) | |
return state.list | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment