Search code examples
javascriptvue.jsvuejs2vue-componentv-model

Selected is not working when i use v-model?


I know that selected does not work if I use v-model, but I use v-model to get the selected user and use it in my firebase, so I have my html like this:

<select v-model="medespeler1" class="inputbox rounded" required>
  <option v-for="(option, i) in medespelers" :key="i" :selected="selected">{{ medespelers[i] }}</option>
</select>

Then in the data property I got this to also get all the medespelers stored in the db and the medespeler1 value:

data: function() {
  return {
    medespelers:[],
    medespeler1: '',
  }
},

In firebase I set all the medespelers in an array and pass it to the data property, but because I need to send the medespeler1 value to the data property I can not use :selected, because that wont work. Where do I start so that it also stores the medespeler1 value and have a selected item in the array?


Solution

  • Since the select is using medespeler1 for v-model, all that must be done is setting the value of medespeler1 and the <select> will react to it:

    new Vue({
      el: "#app",
      data() {
        return {
          medespeler1: "banana"
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <select v-model="medespeler1">
         <option>apple</option>
         <option>banana</option>
         <option>cherry</option>
      </select>
      
      Selected: {{ medespeler1 }}
    </div>