First leave selected select item

Asked

Viewed 616 times

1

Good afternoon, everybody, how are you? Next, I’m listing some courses with v-for and it goes well, however, option needs to be selected and I would like the first item of select to already appear selected, to indicate to the client better...it works, but it’s all blank...it’s not wrong, How do I make the option appear first? Thank you all!! Horatio

<select v-model="cursos" id="cursos" class="form-control" name="cursos">
  <option v-for="item in ListaDeCursos" :value="item.from">
     {{item.from}} 
  </option>
</select>

3 answers

3

The section Basic Usage > Select the documentation addresses this subject:

If the initial value of your v-model Expression does not match any of the options, the element will render in an "unselected" state

Free translation:

If the initial value of the expression in v-model do not match any of the <option>, the element <select> will be rendered in a state unselected.

To do this, just give a valid value to the v-model. Example:

new Vue({
  el: '#app',
  data: {
    opcoes: ['Opção 1', 'Opção 2', 'Opção 3'],
    selecionado: 'Opção 2'
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
  <select v-model="selecionado">
    <option v-for="opcao in opcoes" :value="opcao">
      {{ opcao }}
    </option>
  </select>
</app>

1

Try with the code below.

The idea is to check if the item index is 0. If it is, mark the option as Selected.

<select v-model="cursos" id="cursos" class="form-control" name="cursos">
  <option v-for="(item, index) in ListaDeCursos" :value="item.from" :selected="index == 0">
     {{item.from}} 
  </option>
</select>

0

At the end of the code where you finish loading the list, take the first element from the list

this.cursos = array[0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.