Two way binding computed property with mappers

Viewed 120

I use vuex in my Vue 2 project.

I have this HTML element and I try to implement two way binding:

<input v-model="message">


computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

inside get and set I want to use mappers so the code will look cleaner:

computed: {
  message: {
    get () {
      return ...mapState("obj", ["message"])
    },
    set (value) {
      ...mapMutations("obj/updateMessage", value)
    }
  }
}
    

But I get errors on two rows:

return ...mapState("obj", ["message"])   -   Expression expected.

...mapMutations("obj/updateMessage", value) - Declaration or statement expected.

How can I use mappers inside get and set?

UPDATE: mapMutations and mapState are imported to the component.

1 Answers

You will need to import them first, as you did
import { mapState, mapActions } from 'vuex'
Import actions tho, and not mutations. Indeed, only actions are async and the flow should always be dispatch a action > commit a mutation > state is updated.

Then, plug them where they belong

computed: {
  ...mapState('obj', ['message']),
  // other computed properties ...
}

methods: {
  ...mapActions('obj', ['updateMessage']),
  // other methods ...
}

Then comes the interesting part

computed: {
  message: {
    get () {
      const cloneDeepMessage = cloneDeep(this.message)
      // you could make some destructuring here like >> const { id, title, description } = cloneDeepMessage
      return cloneDeepMessage // or if destructured some fields >> return { id, title, description }
    },
    set (value) {
      this.updateMessage(value)
    }
  }
}

As you can see, I would recommend to also import cloneDeep from 'lodash/cloneDeep' to avoid mutating the state directly thanks to cloneDeep when accessing your state.
This is the kind of warning that the Vuex strict mode will give you, that's why I recommend to enable it in development only.

The official docs are not super explicit on this part (you need to read various parts of them and mix them all together) but it's basically a good way of doing things IMHO.

Related