Using get/set Computed property with mapState, mapMutation in Vuex

时间:2018-09-19 08:25:07

标签: javascript vue.js vuex computed-properties v-model

I have the following computed property using a Vuex module called main:

computed: {
  foo: {
    get(){
      return this.$store.state.main.foo;
    },
    set(value) {
      this.$store.commit("main/foo", value);
    }
  }
}

I want to use the get/set pattern because I want to use v-model="foo". Having to talk to $store directly is all very verbose. Is there an easier way using mapState, mapMutation or even createNamespacedHelpers?

1 个答案:

答案 0 :(得分:2)

我建议您尝试使用 vuex-map-fields 模块,其中包含一个mapFields helper方法,该方法可以帮助您动态设置getter和setter。