Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  131] [ 3]  / answers: 1 / hits: 31873  / 7 Years ago, tue, april 18, 2017, 12:00:00

i have array like this from API:



{select1:Select 1,select2:Select 2,select3:Select 3}


i want to render this array to option list select.



i have tried like this but i dont know how to fill the value and text.
enter


More From » vue.js

 Answers
33

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.


[#58117] Friday, April 14, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingcarloe

Total Points: 677
Total Questions: 109
Total Answers: 96

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
irvingcarloe questions
Wed, Mar 31, 21, 00:00, 3 Years ago
Tue, Aug 4, 20, 00:00, 4 Years ago
Fri, Jul 3, 20, 00:00, 4 Years ago
;