Vuex two way binding

less than 1 minute read

Vuex is very useful library for Vue.js. However… when handling form like input tag with Vuex, setting up two way binding is somehow complicated and you need a job something to do. Without the job, you would encounter an error message on console like below.

Computed property name was assigned to but it has no setter

Of coures, Vuex Guide document is a good solution.

But I want to use mapGetters and mapMutations with Vuex. Without $store, code could be more beautiful. Example is below. Vuex files are ommited.

<template>
  <div>
    <input v-model="something" />
  </div>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex'
import { UPATE_SOMETHING } from '../vuex/mutation_type'

export default {
  methods: {
    ...mapMutations({updateSomething: UPATE_SOMETHING})
  },
  computed: {
    ...mapGetters(['getSomething']),
    something: {
      get () {
        return this.getSomething
      },
      set (value) {
        this.updateSomething(value)
      }
    }
  }
}
</script>

If you want more, vuex-map-fields is helpful. Especially, Multi-row fields may save your life.

Leave a comment