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



我想让time Object的第一个值作为下拉菜单的默认值。每当用户进入网站时,第一个值被选中作为我的默认值。但是,我当前的代码只显示值,但还没有选择值数据。我该怎么做呢?

时间对象:-

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

最新更新