auto select first option in v-for vue js
Asked Answered
S

1

6

I am looping an array to generate dropdown as below

 <select class="form-control" v-model="compare_version" >
            <option
              v-for="(version, index) in allVersions"
              v-bind:value="index"
              v-bind:key="version.versionid"
              :selected="version.versionid === 0"
            >{{ version.versionid }}</option>
          </select>

I am trying to default the value of the dropdown to its first value.

The values are getting displayed but the first option is not getting selected .

What is the mistake in my code. Please help!!

Spiracle answered 10/1, 2020 at 10:50 Comment(1)
Can you add a default value to your v-model?Magdaleno
S
2

You can define the default value as 0 for compare_version in data() since you are binding the index from the iterating list as the value to be captured in the model. v-model will take care of that.

And remove that :selected binding. Taking a note that here captured value from select will be the index of the list.

var vm = new Vue({
  el: "#vue-instance",
  data: {
    compare_version: 0,
    allVersions: [
      {versionId: 'A'},
      {versionId: 'B'},
      {versionId: 'C'}
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
 <!DOCTYPE html>
<html>
<body>
<div id="vue-instance">
<select v-model="compare_version">
    <option v-for="(x,index) in allVersions"
            v-bind:value="index"
            v-bind:key="x.text">{{x.versionId}}</option>
  </select>
  <span>Selected: {{ compare_version }}</span>
</div>
</body>
</html> 
Socialism answered 10/1, 2020 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.