I create a drop-down menu with v-repeat
in Vue.js, and I have a current value where I need to add the selected
property to the select
tag. It seems that v-if
can only be used to control tags, but not properties.
<select name="flavor">
<option value=""></option>
<option v-repeat="proposed_value: proposed_values" value="{{ proposed_value }}">{{ proposed_value }}</option>
</select>
I would need something like this:
<option v-repeat="proposed_value: proposed_values"
value="{{ proposed_value }}"
{{ proposed_value == current_value ? 'selected' }}
>
{{ proposed_value }}
</option>
This is the object used to create the drop-down:
{
"name": "flavors",
"current_value": "strawberry",
"proposed_values": [
"vanilla",
"strawberry",
"lemon"
]
}
Is there a way to do this that does not force me to monkey with the object like this?
{
"name": "flavors",
"proposed_values": [
{"name": "vanilla", "selected": ""}
{"name": "strawberry", "selected": "selected"}
{"name": "lemon", "selected": ""}
]
}
I am using Vue 0.11.10.
In Vue 1.0 and later you can just do this
<div id="app">
<select v-model="selected">
<option value="val1">Text1</option>
<option value="val2">Text2</option>
<option value="val3">Text3</option>
<option value="val4">Text4</option>
<option value="val5">Text5</option>
</select>
</div>
and
new Vue({
el: '#app',
data: {
selected: 'val3'
}
});
So what will be the selected value in data it will be auto selected in dropdown as we set the model. I don't know if it works in older version as I have started from 1.0
note: Vue.js is awesome :)
Ran into this issue myself. Solved it with this.
<select v-model="select">
<template v-for="option in options">
<option v-bind:value="option" v-bind:selected="option == savedOption">{{ option }}</option>
</template>
</select>
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