How to bind radio buttons to a vuex store?

This blogpost put me on the right track. The solution I came up with is this:

<input type="radio" name="info-source" value="1" 
       :checked="infoSource === 1" @change="updateInfoSource(1)">

With the updateInfoSource method committing to the store.

For a complete example look at the following post: How to bind radio buttons to a vuex store?


As the warning states, you cannot modify the value of the Vuex state object outside of a mutation method.

You can make a computed property which has get / set methods to reference / update the state of the relevant data in the Vuex store.

Here's a simple example:

const store = new Vuex.Store({
  state: {
    gender: 'female',
  },
  mutations: {
    SET_GENDER(state, gender) {
      state.gender = gender;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    gender: {
      get() {
        return this.$store.state.gender;
      },
      set(value) {
        this.$store.commit("SET_GENDER", value);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.min.js"></script>
<div id="app">
  <input type="radio" name="gender" value="male" v-model="gender">Male<br>
  <input type="radio" name="gender" value="female" v-model="gender">Female<br>
  <input type="radio" name="gender" value="other" v-model="gender">Other<br>
  Vuex store value: {{ $store.state.gender }}<br>
  Computed property value: {{ gender }}
</div>

Tags:

Vue.Js

Vuex