如何为vuex命名空间模块状态创建getter和setter

时间:2018-05-19 22:21:02

标签: vuejs2 vue-component vuex vuex-modules

如果我有一个名为Vuex的Vuex模块,那么在Vue组件中使用这些状态时,如何为该模块中的状态创建getter和setter?

// My component
new Vue({

 computed: {

   // How do I add setters also below????

   ...mapState('nameSpacedModA', {
       a : state => state.a,
       // ...
   },


   // Following will only add getters..
   // How to add setter ??? 

   ...mapGetters('nameSpacedModA', {
         a: 'a', 
         b: 'b' //, ...
    }
}

我使用v-model将'a'绑定到表单上的文本输入,然后当我编辑控件值时,Vue给出了错误:

  

[Vue警告]:已分配计算属性“a”,但它没有   设定器。

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果你想做2路绑定,你需要在计算属性中定义getter和setter。 (别忘了定义变异updateA

<input v-model="a">
// ...
computed: {
  a: {
    get () {
      return this.$store.state.a
    },
    set (value) {
      this.$store.commit('updateA', value)
    }
  }
}

另一种选择是使用mapFields

答案 1 :(得分:0)

我发现了另一种使用Vuex mapStates和mapActions帮助器的方法。 这稍微冗长一点。因此,使用v-model绑定方法会更好。

// BTW:如果您使用ittus建议的方法,那么您将使用如下的v模型绑定:

<input v-model="a" />

//使用我使用的其他方法,你必须进行双向绑定,如下所示:

<input :value="a" @input="updateA" />

如果你想使用v-model绑定,那么代码将如下所示:

// Vuex store 
....
modules: {ModuleA, ...}


// ModuleA of store
export default {
  namespaced: true,
  states: {
    a: '',
  },

  mutations: {
     updateA: (state, value) => state.a = value
  },

  actions: {
    updateA(context, value) { context.commit('updateA', value) }
  }
}

// Then in your Component you will bind this Vuex module state as below
new Vue({
  store,

  computed: {
     a: {
         get() { this.$store.state.ModuleA.a; }
         set(value) {this.updateA(value);}
      },

  },

  methods: {
    ...mapActions('MyModule', [ updateA ]),
  }
})
相关问题