Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create getters and setters for vuex namespaced module state

If I have a Vuex module which is namespaced, how to create the getters and setters for the states in that module when using these state in Vue components?

// 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' //, ...
    }
}

I am binding 'a' to a text input on a form using v-model and then when I edit the control value, Vue is giving error:

[Vue warn]: Computed property "a" was assigned to but it has no setter.

How to solve this?

like image 984
Andy Avatar asked May 19 '18 22:05

Andy


1 Answers

If you want do do 2 ways binding, you need to defined both getter and setter in computed properties. (Don't forget to define mutation updateA)

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

Another option is using mapFields

like image 150
ittus Avatar answered Sep 29 '22 09:09

ittus