David Marko
David Marko

Reputation: 2519

How to define values for checked and unchecked checkbox with VUE.js?

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?

Upvotes: 18

Views: 29463

Answers (3)

Sphinxxx
Sphinxxx

Reputation: 13017

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'

Upvotes: 44

David
David

Reputation: 326

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>

Upvotes: 2

thesunneversets
thesunneversets

Reputation: 2580

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 : '' }}

Upvotes: 1

Related Questions