在v-for中选择中选择框的第一个选项

Select first option of select box in in v-for

本文关键字:选择 第一个 选项 v-for      更新时间:2023-09-26

我想在下面的选择框中选择第一个选项。这两个我都试过了.el.selected=true;和

if (newValue == 0) return "selected";

但两者都不起作用。

<table class="table table-striped">
    <tr v-for="result in results">
        <select v-model='products[$index].startTime' class="form-control input">
            <option v-for="(timeIndex, time) in result.start_times" v-selected="timeIndex" >@{{ time.start_time }}-@{{ timeIndex }}</option>
        </select>
    </tr>
</table>
Vue.directive('selected', {
    bind: function () {
    },
    update: function (newValue, oldValue) {
        if(newValue==0)
        {
            this.el.selected = true;
        }
        return "";
    },
    unbind: function () {
    }
})

我该怎么做?我做错了什么?有更好的方法吗?

如果您的select绑定到您的v-model,您不需要选择任何特定的选项,Vue知道要将v-model中指定的keypath的值绑定到您在select中传递选项的value。

<option v-for="(timeIndex, time) in result.start_times" :value="timeIndex" >@{{ time.start_time }}-@{{ timeIndex }}</option>

http://vuejs.org/guide/forms.html#Select-选项

但是,您没有设置值。您正在绑定v-selected="timeIndex"。我以前从未见过v-selected,所以我在VueJS文档中查找它,它不会出现,所以除非它是自定义指令,否则它什么都不会做。

试试这个。可以将选定的属性绑定到表达式。如果索引为0,则为true,否则为false

<table class="table table-striped">
    <tr v-for="result in results">
        <select v-model='products[$index].startTime' class="form-control input">
            <option v-for="(timeIndex, time) in result.start_times" :selected="timeIndex === 0" >@{{ time.start_time }}-@{{ timeIndex }}</option>
        </select>
    </tr>
</table>