Search code examples
htmlvue.jsvue-component

using v-model on <select> makes first option not appear in select


My HTML:

<select id='select-id' v-model='position'>
    <option>Opt 1</option>
    <option>Opt 1</option>
</select>

The Vue component:

var app = new Vue({
    el: '#elementid',
    data: {
        name: '',
        position: 'Select Option',
    },
});

When they select an option, I'm using v-model to send that value to the data variable 'name' (will be using this for other things).

However, visually, the select box is blank until I open it and select an option. If I remove the v-model it works as usual with Option 1 being visiable as the preselected option. I've even tried presetting the 'name' to 'Select Option'. I've tried using the html5 'selected disabled' attributes.


Solution

  • You need to use value as well as disabled.
    In this case, the initial value of v-model needs to match the value of the disabled one.

    <div id="app">
      <select id='select-id' v-model='position'>
        <option disabled value="">Select option</option>
        <option>Opt 1</option>
        <option>Opt 1</option>
      </select>
    </div>
    
    var app = new Vue({
      el: '#app',
      data: {
        position: '',
      },
    });
    

    If the initial value of your v-model expression does not match any of the options, the element will render in an “unselected” state. On iOS this will cause the user not being able to select the first item because iOS does not fire a change event in this case. It is therefore recommended to provide a disabled option with an empty value, as demonstrated in the example above.

    Documentation