Search code examples
javascriptvue.jsvuexcomputed-propertiesv-model

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


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?


Solution

  • I'd recommend you to try vuex-map-fields module, which contains a mapFieldshelper method helps you setup getter and setter dynamically.