[英]How to render array to select option vue.js
According to the documentation, v-for
allows you to iterate through the properties of an object. 根据文档, v-for
允许您遍历对象的属性。
In this case, your object is an associative array called reasons
. 在这种情况下,您的对象是一个名为reasons
的关联数组。 This means, that this array has a list of keys and values . 这意味着,此数组具有键和值列表。 The first pair ( key : value ) is "select1"
and "Select 1"
respectively. 第一对( 键 : 值 )分别是"select1"
和"Select 1"
。
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: 好吧,要提取第一个项目"Select 1"
我们需要声明一对别名如key
和item
,然后使用{{...}}
进行插值渲染,在这种情况下, item
别名如下代码示例所示:
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. 请记住,HTML标记select
使用列表中每个项目的option
标记。 Now, this option
tag has a value
parameter and a text
like in this structure: 现在,此option
标记具有value
参数和此结构中的text
:
<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. 因此,我们需要将数组原因的每个key
分配给option
标记的每个value
参数,并将数组原因的value
呈现为option
标记的文本。
<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. 另外,不要忘记v-model
指令,它在表单输入,textarea和select元素上创建双向数据绑定。 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. 我们可以通过在Vue
实例创建中将selected
添加到data
定义并将v-model="selected"
到select
标记来实现此目的。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.