Reputation: 288
I am having two components and i am trying to update the component and i am trying to change value of property based on the checkbox checked or unchecked. I am unable to change the value of the property.
Here is my code:
ComponentA.vue
**Template**
<div class="column" v-for="car in cars">
<label class="label">
<input type="checkbox" v-model="carsSelected" @change="onChange" >
{{ car }}
</label>
</div>
**Script**
data () {
return {
carsSelected: {},
cars: {
hyundai,
maruthi,
audi,
}
}
...
onChange(){
this.$emit('input', this.carsSelected) .---> For updating
}
ComponenrB.vue
<component-a v-model="fourWheeler.brands" />
...
fourWheeler: {}
And here is how fourWheeler.brands looks like:
**It is an object**
{
hyundai: false,
maruti: false,
audi: true,
}
I want to change the values of the car brands ie fourWheeler.brands based on checked or unchecked, if checkbox is unchecked then false, if it is checked then true. Please let me know how to update the values and better way of binding.
Upvotes: 1
Views: 3489
Reputation: 729
Since the checkbox only indicates if it is selected or not, you can't select multiple values with just one checkbox, however you can use your cars object to render the options:
<template>
<main>
<label v-for="(value,key) in cars" :key="key" :for="key">
{{key}}
<input type="checkbox" :id="key" v-model="cars[key]" @change="onChange"/>
</label>
</main>
</template>
<script>
export default {
data(){
return {
cars: {
hyundai:false,
maruthi:false,
audi:false,
}
}
},
methods:{
onChange(){
console.log(this.cars)
}
}
}
</script>
As you can see what I'm doing is iterating through the cars properties and showing a checkbox for each of the properties (each car) and then v-model is changing the specific property of the cars object, so if you do a console.log of the cars object in the onChange
now you see the cars object with the selections. Worth notice that I changed the cars object so it holds the car names and true/false for selected.
Upvotes: 2