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

Time:12-07

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']
  }
});

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related