【问题标题】:Set first value in dropdown as default value in VueJs将下拉列表中的第一个值设置为 VueJs 中的默认值
【发布时间】:2021-10-09 14:34:06
【问题描述】:

我想将time Object 的第一个值设为我的下拉菜单的默认值。每当用户进入网站时,第一个值已被选为我的默认值。但是,我当前的代码仅显示值,但尚未在 vue 数据上选择。我该怎么做?

时间对象:-

{ "1290_1320":"21:30 - 22:00",
  "1320_1350":"22:00 - 22:30",
  "1350_1380":"22:30 - 23:00"
}

下拉 HTML:-

<div class="form-group col-md-8">
   <select id="pickup" class="form-control" @change.prevent="changeTime($event)">
      <option selected="selected" v-for="(time, i) in this.timeslots" :key="i" 
       :value="time">{{time}}</option>
   </select>
</div>

Vue:-

export default {
  data() {
    return {
      selectedTime: null
    }
  },
  methods: {
     changeTime(event) {
       this.selectedTime = event.target.options[event.target.options.selectedIndex].text;
  }

下拉 javascript:-

// remove "selected" from any options that might already be selected
$('#pickup option[selected="selected"]').each(
    function() {
        $(this).removeAttr('selected');
    }
);

// mark the first option as selected
$("#pickup option:first").attr('selected','selected');

【问题讨论】:

  • 只需为 SELECT 标记提供 v-model - 并确保使用选项数组中的第一个元素初始化模型变量。
  • 如果我设置 &lt;select v-model="selectedTime"&gt;&lt;/select&gt; ,那么我应该在我的 selectedTime in data() return 上设置什么? :/ @IVOGELOV
  • 如果时隙是预定义/硬编码的 - 那么它必须等于第一个 OPTION 标签的value 属性。如果您通过 AJAX 获取插槽 - 使用 NULL 对其进行初始化,一旦获取插槽,将其分配给对象中第一个插槽的键。
  • 时间会动态变化,如何将其设置为每次下拉菜单的第一个值? @IVOGELOV 抱歉,我是新手,不太了解 T-T

标签: javascript vue.js bootstrap-4 vuejs2 dropdown


【解决方案1】:

这取决于您的特定用例,但通常您可以执行以下操作:

<div class="form-group col-md-8">
   <select id="pickup" v-model="selectedTime" class="form-control">
      <option v-for="(timeValue, timeID) in timeslots" :key="timeID" :value="timeID">{{ timeValue }}</option>
   </select>
</div>
<script>
import axios from 'axios';

export default
{
  name: 'MyDropDown',
  data() 
  {
    return {
      selectedTime: null,
      timeSlots: {},
    }
  },
  created()
  {
    this.fetchData();
  },
  methods: 
  {
    fetchData()
    {
      axios.get('/api/getTimeSlots').then(response =>
      {
        this.timeSlots = response.data;
        this.selectedTime = Object.keys(response.data)[0];
      });
    },
  }
}

【讨论】:

    猜你喜欢
    • 2014-07-07
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2020-07-06
    • 2016-11-16
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多