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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With