Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue.js how to display a default value in a selector as well as sort the options?

I have an application with vue.js and I run into a problem, I have a selector with options in the options array.
But when I display the page there is no value in this selector, basically I would like it to take the first base value but I have no idea how to do it.
Before I do that I would also like to sort the options array against the sorted array.
Thanks in advance.

Code : https://codepen.io/pronicio/pen/eYGJjMP

<div id="app">
  <select v-model="selected">
    <option v-for="option in options" v-bind:value="option">
      {{ option }}
    </option>
  </select>
  <span>Selected : {{ selected }}</span>
</div>
new Vue({
  el: '#app',
  data: {
    selected: '',
    options: [ 'A', 'B', 'C'],
    sorted: [ 'B', 'C']
  }
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re using a very old version of vue in your codepan. Update the version. You can add the selected option into the mounted hook. If you get the options by any api. Choose the selected one after getting the response.

new Vue({
  el: '#app',
  data: {
    selected: '',
    options: [ 'A', 'B', 'C'],
    sorted: [ 'B', 'C', 'A']
  },
  mounted(){
    this.selected =  this.options[0]
    
  }
});
@import url(https://fonts.googleapis.com/css?family=Open+Sans);

body {
  font-family: 'Open Sans', sans-serif;
  background: rgba(0,0,0,.5);
  margin: 0;
}

#app {
  width: 500px;
  margin: 0 auto;
  padding: 10px 20px;
  background: rgba(255,255,255,.9);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="selected">
    <option v-for="option in options" v-bind:value="option">
      {{ option }}
    </option>
  </select>
  <span>Selected : {{ selected }}</span>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading