v-model on <select> sets the value to undefined if the <select> is lacking the matching <option>
See original GitHub issueLet’s say we have a variable called someVar in our component - it is properly defined and its initial value is 1:
...
data: {
someVar: 1
}
...
In our template there is a select tag with 3 options bound to someVar with v-model:
<select v-model="someVar">
<option value="1">Option 1</option>
<option value="3">Option 3</option>
<option value="5">Option 5</option>
</select>
At this point everything works as expected. However, if we then change the value of someVar to a value that is not covered by any of the option tags (2 in this example), v-model will set someVar to undefined instead:
...
created: function() {
setTimeout(function(){
this.someVar = 2;
// this.someVar becomes undefined instead
}.bind(this), 2000);
}
...
Here is a jsfiddle showing the issue: https://jsfiddle.net/0vpqny9y/4/
What I expected to happen was that the value is set properly and the select tag becomes empty.
While the setTimeout example may be silly, where it’s becoming a pain to me is when I load both the options and the model that has a property bound to the select at the same time, which results in a race condition:
- Options load first, model loads second, the option is present so everything works fine.
- Model loads first, the bound value is set to whatever was loaded through AJAX, but since there are no options yet the value is instead set to undefined, then the options load by this time the original value is lost
Issue Analytics
- State:
- Created 7 years ago
- Reactions:12
- Comments:14 (3 by maintainers)
Top GitHub Comments
Not sure if this is the “right” way, but I got around this issue with async options by using
v-if
on the component to not render it until the async operation was complete.https://jsfiddle.net/paulredmond/a085bpmn/2/
I was also confused by this. If this is the expected behavior, it may be helpful to mention this in the Form Input Bindings -> Select section of the documentation.