18

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 3

44

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'
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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

1

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

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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.