0
votes

I have an HTML select that is pre-populated with options from a server. When I use v-model, it selects an empty option when the page loads instead of the first option.

I found the post below as a possible solution, however, the data is populated from the server so I don't know what the first option will be.

Vue selected first option with v-model

<select id="group" v-model="group">
  <option value="Color">Color</option>
  <option value="Size">Size</option>
</select>
2

2 Answers

1
votes

I found the answer after a little more digging:

HTML:

<select id="group" ref="groupSelect" v-model="group">
  <option value="Color">Color</option>
  <option value="Size">Size</option>
</select>

JS:

mounted: function() {
  var groupSelect = this.$refs.groupSelect.children;

  if (groupSelect.length) {
    this.group = groupSelect[0].value;
  }
}
0
votes

See this JS Fiddle: https://jsfiddle.net/eywraw8t/147653/

In this case, you can use a watcher to check if the list of options has changed and from this, you can have the chance to assign the default value to the group based on the value of the first option.