【问题标题】:Select first option of select box in in v-for在v-for中选择选择框的第一个选项
【发布时间】:2016-05-08 13:00:12
【问题描述】:

我想在下面的选择框中选择第一个选项。我已经尝试过 this.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 () {

    }
})

我该怎么做呢?我究竟做错了什么?有没有更好的办法?

【问题讨论】:

  • 你可以在你的 v-for 循环中做 :selected="$index === 0" ,你不需要指令

标签: javascript vue.js


【解决方案1】:

如果您的 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-Options

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

【讨论】:

  • 他的代码显示他正在创建一个自定义指令
【解决方案2】:

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

<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>

【讨论】:

    猜你喜欢
    • 2020-04-28
    • 2018-04-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多