I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element.
- Triggering the action
deleteOption(path, key)
{ this.$store.dispatch('deleteOptionAction', {path, key}) }
- Executing the mutation
deleteOptionAction ({ commit }, payload) { commit('deleteOption', payload) }
- The mutation is passed with the payload where the path is 'state.xmlValues.Offers[0].data.Pars' and the key is 0
deleteOption (state, payload) {
let stt = eval('state.' + payload.path)
Vue.delete(stt, payload.key)
// delete stt[payload.key] - works the same as Vue.delete
state.xmlValues.Offers[0].data.Pars = Object.assign({}, Object.values(stt))
}
I attempted using the state[payload.path] syntax, but it did not work. The path contains the string 'state.xmlValues.Offers[0].data.Pars', so I used let stt = eval('state.' + payload.path) to make it function. However, deleting an element from the state posed a challenge: when Vue.delete(stt, payload.key) is used, it only removes the element key locally stored in stt variable, rather than in the state itself.
Subsequently, I updated the state objects with stt (from which the required element was already deleted), hardcoding the path - something I aim to avoid:
state.xmlValues.Offers[0].data.Pars = Object.assign({}, Object.values(stt))
How can I send a path to the store, then utilize it to erase an object in the state without explicitly coding the path?
Similarly, for my other mutation addOption, I utilized a dynamic path to the state object - and achieved success by evaluating the dynamic path within stt
addOption (state, payload) {
let stt = eval('state.' + payload.path)
Vue.set(stt, payload.key, payload.newEl)
}