Skip to content

v-model on <select> sets the value to undefined if the <select> is lacking the matching <option> #4524

@kordian-kowalski

Description

@kordian-kowalski

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

  1. Options load first, model loads second, the option is present so everything works fine.
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions