将下拉列表中的第一个值设置为 VueJs 中的默认值

Set first value in dropdown as default value in VueJs

我想将 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');

这取决于您的特定用例,但通常您可以这样做:

<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];
      });
    },
  }
}