Created
November 7, 2018 09:58
-
-
Save vertcitron/eb6b9aab12d69b9fac3b4b9688320a1d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** VUEX module for image asset management **/ | |
import Vue from 'vue' | |
export default { | |
namespaced: true, | |
// ----------------------------------------------------------------- | |
state: { | |
asset: {} | |
}, | |
// ----------------------------------------------------------------- | |
getters: { | |
asset: state => state.asset, | |
slot: state => name => { | |
for (const slot of asset.slots) { | |
if (slot.name === name) return slot | |
} | |
return undefined | |
} | |
}, | |
// ----------------------------------------------------------------- | |
mutations: { | |
setSlot: (state, newSlot) => { | |
const slots = [] | |
// pushing first other existing slots to this temporary array | |
// if one have the same name than newSlot, it will be ignored | |
for (const slot of state.assets.slots) { | |
if (slot.name !== newSlot.name) { | |
slots.push(slot) | |
} | |
} | |
// then adds the newSLot | |
slots.push(newSlot) | |
// and replace in state data. The slice breaks any old reference | |
Vue.set(state.asset, 'slots', slots.slice(0)) | |
} | |
}, | |
// ----------------------------------------------------------------- | |
actions: { | |
read: (context, id) => { | |
// don't forget that an action should return a promise | |
return Vue.$axios.get(`asset/${id}`) | |
.then(response => { | |
// using Vue.set to be sure that sub-properties are reactive | |
Vue.set(context.state, 'asset', response.data) | |
return Promise.resolve(context.state.asset) | |
}) | |
.catch(error => { | |
// empties state in case of an API error | |
Vue.set(context.state, 'asset', {}) | |
return Promise.reject(error) | |
}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment