我想在我的自定义日期时间组件上使用v模型:
<date-time-picker v-model="startDate" label="Start date"></date-time-picker>
所以我在DateTimePicker.vue中所做的是:
<template>
<v-menu v-model="menu" :close-on-content-click="false" full-width max-width="290" transition="scale-transition">
<!-- Text field -->
<v-text-field slot="activator" :label="label" append-icon="date_range" solo
:value="formattedDate" @input="handleDateTime"></v-text-field>
<!-- Date picker -->
<v-date-picker v-model="selectedDate" locale="fr-fr" v-if="datePicker" :min="todayDate">
<v-spacer></v-spacer>
<v-btn flat color="primary" @click="menu = false">Cancel</v-btn>
<v-btn flat color="primary" @click="chooseDate">OK</v-btn>
</v-date-picker>
<!-- Time picker -->
<v-time-picker v-if="!datePicker" v-model="selectedTime" full-width format="24hr" :min="todayTime">
<v-spacer></v-spacer>
<v-btn flat color="primary" @click="menu = false">Cancel</v-btn>
<v-btn flat color="primary" @click="chooseTime">OK</v-btn>
</v-time-picker>
</v-menu>
</template>
<script>
import format from 'date-fns/format'
export default {
name: "DateTimePicker",
props: ['label', 'value'],
data() {
const todayDate = new Date().toISOString().substr(0, 10);
const todayTime = new Date().getHours() + ':' + new Date().getMinutes();
return {
dateValue: '',
timeValue: '',
todayDate,
todayTime,
selectedDate: todayDate,
selectedTime: todayTime,
datePicker: true,
timePicker: false,
menu: false
}
},
methods: {
// Triggered by clicking on OK button inside Datepicker
chooseDate: function () {
this.dateValue = this.selectedDate;
this.datePicker = false;
},
// Triggered by clicking on OK button inside Timepicker
chooseTime: function () {
this.timeValue = this.selectedTime;
this.menu = false;
},
handleDateTime: function () {
this.$emit('input', this.formattedDate);
}
},
computed: {
// Format date
formattedDate() {
return this.dateValue && this.timeValue ? format(this.dateValue, 'DD/MM/YYYY') + ' at ' + this.timeValue : '';
}
},
watch: {
// Display date picker when the menu is closed
menu: function (opened) {
if (!opened) this.datePicker = true;
}
}
}
</script>
<style scoped>
</style>
但是当我选择日期时不会触发@input
事件,因此永远不会调用handleDateTime
。
我不明白怎么了,您能帮我吗?也许在组件上使用v模型是不可能的,而我不得不使用另一种方法?
答案 0 :(得分:1)
您像以前一样保留父代码的代码:
<date-time-picker v-model="startDate" label="Start date"></date-time-picker>
在子组件中,为formattedDate
属性添加一个观察者,如下所示:
watch:{
....
formattedDate(v) {
this.$emit('input', this.formattedDate)
}
}