<select> as sub component with <option> null value results in weird behavior
Version
3.0.7
Reproduction link
https://codesandbox.io/s/distracted-ritchie-kdcwo?file=/src/components/DistanceSelect.vue
Steps to reproduce
See repo
What is expected?
Both <select>
should behave the same. Since the value of the component is null
, the first <option>
should be selected.
What is actually happening?
The <select>
in the sub component does not show the initial value. Right now, you have to change the value to something else and then back. Also, when only using Number
as type, it doesn't even work when changing values.
The reason why this is happening is because the <option>
with value null
in the subcomponent is rendered as <option value="null">
while the one in the main component is rendered as <option value="">
. So the subcomponent compares null
to "null"
I guess.
Also, when the amount of options are lowered, it actually works as expected.
Native events always have strings. This is normal. You need to use v-model
to allow null
(and any other non string value):
<template>
<select v-model="localValue">
<option :value="null">Not set</option>
<option :value="10">10</option>
<option :value="20">20</option>
</select>
</template>
<script>
export default {
props: {
modelValue: {
type: [String, Number, null],
default: null,
},
},
computed: {
localValue: {
get() {
return this.modelValue
},
set(value) {
this.$emit('update:modelValue', value)
}
}
},
emits: ["update:modelValue"],
methods: {
update($event) {
console.log("update", typeof $event.target.value, $event.target.value);
this.$emit("update:modelValue", $event.target.value);
},
},
};
</script>
Remember to use the forum or the Discord chat to ask questions!
How is it normal that two components that are exactly the same, but just with a fewer amount of options, are rendered differently?
That happens because the option being selected does not reflect the actual value being sent:
you are setting "null"
or ""
instead of actually setting null
which updates the value to no option on the other custom select while keeping the option you just clicked selected. But that's because the browser keeps it that way. Using the correct approach makes it work
Okay, but there is still something strange going on when a <select>
isn't tiny. If you click submit
on this url you will see that they behave differently. The url will change to: https://kdcwo.csb.app/?small=&large=null
. So, if a <select>
is larger than X, the null
value is rendered as a string.
This was also the initial actual issue, just had to boil it down a bit.
I created a Vue 2 sandbox, and this DOES NOT happen in vue 2: https://codesandbox.io/s/focused-glade-qj11z?file=/src/main.js