user1692333
user1692333

Reputation: 2597

How to use Vue computed setters with checkbox?

I have a list of checkboxes:

<ul>
    <li v-for="system in payment_systems">
        <input type="checkbox" :id="'ps-' + system.id" v-bind:value="system" v-model="checked_payment_systems">
        <label :for="'ps-' + system.id">{{ system.translated.name }}</label>
    </li>
</ul>

And I need to store checked items to Vuex so I use computed properties like this:

computed: {
    checked_payment_systems: {
        get() {
            return this.$store.state.program.payment_systems;
        },
        set(payment_systems) {
            console.log(payment_systems)
        }
    }
},

The problem is that in setter I get only true/false instead of object or array of objects.

Upvotes: 0

Views: 815

Answers (1)

Efrat Levitan
Efrat Levitan

Reputation: 5622

the computed property you defined v-models with an input value. the set property will be called on with the input value. in your example, you are binding the same get-set to all of your checkboxes. it should be done differently.

if i where you, i would remove the v-model and manually declare a function to happen onchange and a value, and pass them the a key, yo get the specific value in my object.

i made for you an example: https://jsfiddle.net/efrat19/p87ag0w3/1/

const store = new Vuex.Store({
  state: {
    program:{
        payment_systems:{'paypal':false,'tranzila':false},
    }
  },
  mutations:{
    setPayment(state,{system,value}){
    	state.program.payment_systems[system]=value;
    }
  },
  actions:{
    setPayment({commit},{system,value}){
 
    	commit('setPayment',{system,value})
    }
  }
})

const app = new Vue({
	store,
  el: '#app',
  data() {
  },
  computed: {
  	 checked_payment_systems(){
     return system=>
            this.$store.state.program.payment_systems[system]
     }
  },
  methods:{
  	setValue(system,value){
    	this.$store.dispatch('setPayment',{system,value})
    }
}});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="
https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.js"></script> 
<div id="app">
   <li v-for="(value,system) in $store.state.program.payment_systems">
        <input type="checkbox" :id="'ps-' + system.id" :checked="checked_payment_systems(system)" @change="setValue(system,$event.target.checked)">
        <label :for="'ps-' + system.id" >{{system}}</label>
    </li>
    <br>
    values in the store:
    <br>
    <br>
{{$store.state.program.payment_systems}}
</div>

Upvotes: 1

Related Questions