1

我想在我的自定义日期时间组件上使用 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 而我必须使用另一种方式?

4

1 回答 1

1

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

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

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

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

   }

full running code

于 2019-01-21T13:38:00.217 回答