[Vuejs]-V-model on Component returning type string instead of type null

0👍

It’s related to how <option> gives you a value. null is an absence of a value. If the value of the option is nullish, then text between opening and closing tags returned. Try use "0" instead of null and check for "0", not null, and then replace "0" with null if you really need null

0👍

If you need to retain the values original type then you must use a computed getter / setter within the component along with a v-model binding.

Demo Here

Working Code

export default defineComponent({
    computed: {
        value: {
            get() {
                return this.modelValue;
            },
            set(value: any) {
                this.$emit('update:modelValue', value);
            }
        }
    },
    data() {
        return {
            selectOptions: {
                'Null Option': null,
                'Numeric Option': 1,
                'String Option': 'String'
            }
        }
    },
    emits: ['update:modelValue'],
    name: 'HtmlSelect',
    props: {
        modelValue: {
            type: String,
            default: null
        }
    },
    template: '<select v-model="value">' +
        '<option v-for="(option, i) in selectOptions" :value="option">{{ i }}</option>' +
        '</select>'
})

Leave a comment