VueJS 在自定义组件日期时间选择器上使用 v-model

VueJS use v-model on custom component date time picker

我想像这样在我的自定义日期时间组件上使用 v-model :

<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-model 而我必须使用其他方式?

您像以前一样保留父代码的代码:

<date-time-picker v-model="startDate" label="Start date"></date-time-picker>

在子组件中为 formattedDate 属性 添加观察者,如下所示:

   watch:{
       ....
     formattedDate(v) {
        this.$emit('input', this.formattedDate)
    }

   }

full running code