Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally set selected option in Vue

Is it possible to pre-set a select box's selected value?

Using Vue (v2), I have tried to create a select box like this inside a Vue template.

<select v-model="selectedFlavor">
   <option v-for="flavor in flavors" 
           :value="flavor"
           :selected="selectedFlavor == flavor">{{ flavor }}</option>
</select>

And a component like this:

Vue.component('flavor-pane', {
      ...
      data: function() {
          selectedFlavor: 'strawberry',
          flavors: ['blueberry', 'lime', 'strawberry'],
      });
}

Essentially, the idea is that I need to loop through a simple array, create several options in a select box, and set the select box's value to an existing value. Can I do this?

My templates/components are rendering fine, but the selected attribute doesn't seem to appear in the HTML even when the condition is met and there is no value selected in the select box.

like image 517
rob Avatar asked Jan 23 '18 18:01

rob


1 Answers

Yes, it is possible. I've created this example https://jsfiddle.net/Luvq9n4r/2/ to help you. To change the value selected just set the model. If it isn't what you need, please, make a fiddle too.

Thank you.

new Vue({
  el: '#app',
  data: function() {
    return {
      selectedFlavor: 'lime',
      flavors: ['blueberry', 'lime', 'strawberry']
    }
  },
  methods: {
    change: function() {
      this.selectedFlavor = 'strawberry';
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <button @click="change()">Set Strawberry</button>
  <select v-model="selectedFlavor">
    <option v-for="flavor in flavors" :value="flavor">{{flavor}}</option>
  </select>
</div>
like image 148
lmarqs Avatar answered Sep 19 '22 13:09

lmarqs