Is there a way how define checked and unchecked value for .? Now VUE sets model to true/false which makes sense but in real apps data format is somethink like '1' => true and ''=>false. How to achive this in VUE?
3 Answers
You can use true-value and false-value:
https://v2.vuejs.org/v2/guide/forms.html#Checkbox-1
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
// when checked:
vm.toggle === 'yes'
// when unchecked:
vm.toggle === 'no'
1 Comment
Murtaza
Hi, do you know how I color these value if it's Yes it print yes in green and if it's No it print No in red
If you need to wrap a field in a component, then the code will have to be slightly modified.
<template>
<div class="flex items-center h-5">
<input
@input="$emit('input', reversedValue)"
:id="id"
:value="value"
type="checkbox"
:checked="checked"
/>
</div>
</template>
<script>
export default {
props: {
value: [Boolean, String, Number],
trueValue: {
type: [Boolean, String, Number],
default: true
},
falseValue: {
type: [Boolean, String, Number],
default: false
},
},
computed: {
reversedValue() {
return this.value === this.trueValue ? this.falseValue : this.trueValue;
},
checked() {
return this.value === this.trueValue;
}
}
};
</script>
Comments
Not sure what it is exactly you need, but, as you say, if you do:
{{ boxtest }}
<input type="checkbox" v-model="boxtest"/>
Boxtest will display as 'true' or 'false' as you check or uncheck the box.
If you do need to convert it you could just do the likes of:
{{ boxtest ? 1 : '' }}
2 Comments
David Marko
Problem is with the REST communication. My database data has '1':'' values and the same I need when posting this data back. I cant post true/false and I dont have tru/false values in my data
thesunneversets
If you set boxtest to '1' or '' in the above example it will check and uncheck the box in the way you'd expect... Vue sees those values as truthy and falsy.