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!!

1
  • Can you add a default value to your v-model? Commented Jan 10, 2020 at 10:53

1 Answer 1

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> 

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.