Skip to content

Instantly share code, notes, and snippets.

@vertcitron
Last active November 7, 2018 10:47
Show Gist options
  • Save vertcitron/c9b879df6655ef17ad31f9ee88d4fc3c to your computer and use it in GitHub Desktop.
Save vertcitron/c9b879df6655ef17ad31f9ee88d4fc3c to your computer and use it in GitHub Desktop.
/** 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 state.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