gpt4 book ai didi

javascript - 在 v-for vue js 中自动选择第一个选项

转载 作者:行者123 更新时间:2023-12-03 12:25:15 25 4
gpt4 key购买 nike

我正在循环一个数组以生成如下下拉列表

 <select class="form-control" v-model="compare_version" >
<option
v-for="(version, index) in allVersions"
v-bind:value="index"
v-bind:key="version.versionid"
:selected="version.versionid === 0"
>{{ version.versionid }}</option>
</select>

我正在尝试将下拉列表的值默认为其第一个值。

值正在显示,但第一个选项没有被选中。

我的代码中有什么错误。请帮忙!!

最佳答案

您可以将 compare_version 的默认值定义为 0在 data()因为您将迭代列表中的索引绑定(bind)为要在模型中捕获的值。 v-model会处理的。

并删除 :selected捆绑。请注意,此处从 select 中捕获的值将是列表的索引。

var vm = new Vue({
el: "#vue-instance",
data: {
compare_version: 0,
allVersions: [
{versionId: 'A'},
{versionId: 'B'},
{versionId: 'C'}
]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!DOCTYPE html>
<html>
<body>
<div id="vue-instance">
<select v-model="compare_version">
<option v-for="(x,index) in allVersions"
v-bind:value="index"
v-bind:key="x.text">{{x.versionId}}</option>
</select>
<span>Selected: {{ compare_version }}</span>
</div>
</body>
</html>

关于javascript - 在 v-for vue js 中自动选择第一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59680207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com