How to bind checkboxes to Vuex store

checkboxvuejs2vuex

I have a component that contains some checkboxes. I need to be able to access which checkboxes are checked from other components in my Vue application, but I cannot for the life of me figure out (nor find online) how to properly connect the checkboxes to my Vuex store.

What is the right way to connect checkboxes within a component to a Vuex store, so that they act just as if the checkbox was connected to the components data via v-model?

Here is a starting point for what I'm trying to do (in a very very basic sense)

https://jsfiddle.net/9fpuctnL/

<div id="colour-selection">
  <colour-checkboxes></colour-checkboxes>
</div>

<template id="colour-checkboxes-template">
  <div class="colours">
    <label>
      <input type="checkbox" value="green" v-model="colours"> Green
    </label>
    <label>
      <input type="checkbox" value="red" v-model="colours"> Red
    </label>
    <label>
      <input type="checkbox" value="blue" v-model="colours"> Blue
    </label>
    <label>
      <input type="checkbox" value="purple" v-model="colours"> Purple
    </label>
    
    <chosen-colours></chosen-colours>    
  </div>
</template>

<template id="chosen-colours-template">
  <div class="selected-colours">
      {{ colours }}
    </div>
</template>

const store = new Vuex.Store({
  state: {
    colours: []
  }
});

Vue.component('colour-checkboxes', {
  template: "#colour-checkboxes-template",
  data: function() {
    return {
      colours: []
    }
  }
});

Vue.component('chosen-colours', {
    template: "#chosen-colours-template",
  computed: {
    colours() {
        return store.state.colours
    }
  }
});

const KeepTalkingSolver = new Vue({
  el: "#colour-selection"
});

The aim is to get the colours that are selected in the colour-checkboxes component to output in the chosen-colours component, going through the Vuex store.

Best Answer

You can use computed property with getter as vuex getter and setter in computed property which will call a mutation for that state property to do this.

You can see an example of this here with two-way Computed Property:

<input v-model="message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}
Related Topic