预选VUE2下拉菜单

时间:2020-07-23 09:05:38

标签: vue.js vuejs2

我有一个vue2应用程序,我需要预先选择一个dropdown,但对于我一生来说,我无法弄清楚。

我已经查看并尝试了以下所有内容:

How to preselect current value in a select created with v-repeat in Vue.js

普通HTML

<select ref="courierList" id="courierList" class="form-control" v-model="shippingDetails.selectedCourier" @change="selectedCourierDd">
    <option :value="courier.name" v-for="(courier, i)  in couriers" :key="i">
        {{ courier.name }}
    </option>
</select>
data() {
   return {
       couriers: [],
       .... OTHER DATA ITEMS
   }
},

beforeMount() {
    this.fetchCouriers();
},

fetchCouriers() {
    axios.get('/couriers')
        .then((response) => {
             this.couriers = response.data.couriers;
             .... OTHER CODE

尝试输入的代码> 1

将以下内容添加到option

selected="{{ courier.name === preselectedCourierName ? 'true' : 'false' }}">

也没有true / false

尝试过的代码> 2

将以下内容添加到option

v-bind:selected="courier === preselectedCourierName"

及以下

data() {
    return {
        .... OTHER DATA ITEMS
        preselectedCourier: [],
        preselectedCourierName: ''
}

 fetchCouriers() {
     axios.get('/couriers')
         .then((response) => {
             this.couriers = response.data.couriers;
             .... OTHER CODE
             console.log('couriers', this.couriers[0])
             this.preselectedCourier = this.couriers[0];
             this.preselectedCourierName = this.preselectedCourier.name;

             console.log('preselectedCourier', this.preselectedCourier)
             console.log('preselectedCourierName', this.preselectedCourierName)

给予 enter image description here

尝试过的代码> 3

<option :value="courier.name" v-for="(courier, i)  in couriers" :key="i" :selected="courier.name === 'APC'">

没有错误,但下拉菜单仍未预选

1 个答案:

答案 0 :(得分:0)

此修复程序位于mounted的{​​{1}} hook集中v-model

select
<select v-model="shippingDetails.selectedCourier">

确切地给我想要的东西

enter image description here