首页 > 解决方案 > 预选 VUE2 下拉菜单

问题描述

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

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

如何在 Vue.js 中使用 v-repeat 创建的选择中预选当前值

普通 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)

在此处输入图像描述

尝试代码> 3

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

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

标签: vue.jsvuejs2

解决方案


修复是在mounted hook集合v-modelselect

<select v-model="shippingDetails.selectedCourier">
mounted() {
    this.shippingDetails.selectedCourier = 'APC';
}

给我我想要的

在此处输入图像描述


推荐阅读