Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Vue向多个模块添加可重用的变体_Javascript_Vue.js_Vuex - Fatal编程技术网

Javascript Vue向多个模块添加可重用的变体

Javascript Vue向多个模块添加可重用的变体,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我有一个变种可以跨多个vuex模块重用,但会在模块级别修改状态。如何将突变分离出来,以便在不重复代码的情况下将其放入每个模块的突变中 const state = { fieldInfo: {} } const actions = { async getOptions({ commit }) { commit('setOptions', await Vue.axios.options('/')) } } const mutations = { setOptions(st

我有一个变种可以跨多个vuex模块重用,但会在模块级别修改状态。如何将突变分离出来,以便在不重复代码的情况下将其放入每个模块的突变中

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
}

有人可能会有更好的答案。但在其当前状态下,“fieldInfo”是vuex的共享属性。这就像说window.somVar并期望someVar是一个不同的实例,这取决于使用它的模块。如果不声明一个类的新实例等,这实际上是不可能的。在最基本的级别上,您需要类似于
fieldInfo{moduleA:val,moduleB:val}

的东西,因为您已经将存储命名为命名空间,这应该可以很好地工作。您所需要做的就是将变异函数移动到它自己的文件中,然后将其导入到您需要的存储中

export default function (state, value) {
  // long mutation happens here
  state.fieldInfo = value
}
然后在你的店里

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
}