Reputation: 6127
I have a mutation can be reused across multiple vuex modules but modifies the state at a module level. How can the mutation be separated out so that it can be dropped into each module's mutations without having to repeat the code?
const state = {
fieldInfo: {}
}
const actions = {
async getOptions({ commit }) {
commit('setOptions', await Vue.axios.options('/'))
}
}
const mutations = {
setOptions(state, value) {
// long mutation happens here
state.fieldInfo = value
}
}
export default {
namespaced: true,
state,
actions,
mutations
}
Upvotes: 0
Views: 340
Reputation: 6739
As you already have your stores namespaced this should work perfectly. All you need to do is move the mutation function to it's own file and then import it in the stores that you need it.
export default function (state, value) {
// long mutation happens here
state.fieldInfo = value
}
Then in your store
import setOptions from './setOptions.js'
const state = {
fieldInfo: {}
}
const actions = {
async getOptions({ commit }) {
commit('setOptions', await Vue.axios.options('/'))
}
}
const mutations = {
setOptions
}
export default {
namespaced: true,
state,
actions,
mutations
}
Upvotes: 2
Reputation: 341
Someone will probably have a better answer. But in its current state 'fieldInfo' is a shared vuex property. It's like saying window.somVar and expecting to have someVar be a different instance depending on what module is using it. That's not really possible without declaring a new instance of a class, etc. At the most basic level you would need something more like fieldInfo{moduleA: val, moduleB: val}
Upvotes: 0