Search code examples
selectvue.jsvuejs2bootstrap-vuevue-select

How to set value from bootstrap-vue-select control to be pre-selected on form load?


I'm using VueJS, or to be more precise Bootsrap-Vue (select form type). In the template I have the following code:

<b-form-select>                   
  <option v-for="(selectOption, indexOpt) in item.select.options" 
         :selected="selectOption == item.select.selected ? 'selected' : ''"
         :key="indexOpt"
         :value="selectOption"
  >
    {{ selectOption }} - {{ selectOption == item.select.selected }}
  </option>
</b-form-select>

Where the corresponding data is defined as:

let item = {
  label: "some text goes here",
  inputType: 'text',
  select: {
      selected: '15',
      options: [
         '5',
         '10',
         '15',
         '20'
      ]
  }
}

From the output in the UI, we can see that the condition is evaluated properly (condition for checking the item "15" is returning "true"). Here how the select control looks like:

enter image description here

If I inspect the HTML it looks like:

enter image description here

BUT, what I need here is, to be able during loading the control, the passed param into "item.select.selected" to actually show which option from the select control to be pre-select (on page loads). In many options that I tried, my select control is not selected on page load.

Is there any way to achieve this?


Solution

  • You can bind the default value directly to <select> with v-model. If you bind it to item.select.selected it should show it in the select.

    <b-form-select v-model="item.select.selected">                   
        <option v-for="(selectOption, indexOpt) in item.select.options" 
            :key="indexOpt"
            :value="selectOption"
        >
            {{ selectOption }} - {{ selectOption == item.select.selected }}
        </option>
    </b-form-select>
    

    Here's your code with the default value displayed: https://jsfiddle.net/adampiziak/eywraw8t/146114/

    docs: https://v2.vuejs.org/v2/guide/forms.html#Select
    another answer: Set default value to option select menu