How to render array to select option vue.js
You should look over the documentation for list rendering an object.
<select>
<option v-for="(reason, key) in reasons"
:value="key"
:key="key">
{{reason}}
</option>
</select>
Example.
According to the documentation, v-for
allows you to iterate through the properties of an object.
In this case, your object is an associative array called reasons
. This means, that this array has a list of keys and values. The first pair (key:value) is "select1"
and "Select 1"
respectively.
How to render the values of these pairs?
Well, to extract the first item "Select 1"
we need to declare a pair of alias like key
and item
and then render it by interpolation using {{...}}
in this case the item
alias as shown in this code sample:
var selector = new Vue({
el: '#selector',
data: {
selected: '',
reasons: {
"select1": "Select 1",
"select2": "Select 2",
"select3": "Select 3",
"select4": "Select 4",
"select5": "Select 5",
"select6": "Select 6",
"select7": "Select 7"
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="selector">
<select v-model="selected">
<option v-for="(item, key) in reasons" :value="key">
{{item}}
</option>
</select>
<br>
<br>
<span>Selected: {{ selected }}</span>
</div>
Update
Remember that the HTML tag select
uses the option
tag for each item of the list. Now, this option
tag has a value
parameter and a text
like in this structure:
<select>
<option value="select1">Select 1</option>
...
<option value="select7">Select 7</option>
</select>
So, we need to assign each key
of the array reasons to each value
parameter of the option
tag and render the value
of the array reasons as the text of the option
tag.
<option v-for="(item, key) in reasons" :value="key">
{{item}}
</option>
Also, do not forget about v-model
directive, which creates two-way data bindings on form input, textarea, and select elements. This means, it automatically picks the correct way to update the element based on the input type. We can achieve this by adding selected
to the data
definition in the Vue
instance creation and adding v-model="selected"
to the select
tag.