基于vant的可选择时间段的日历组件

510 阅读1分钟
        <van-field
          readonly--------这个一定要加上,否则在弹出框的时候会将键盘调出来
          required
          name="datetimePicker"
          :value="form.originTime"
          label="时间"
          placeholder="请选择时间"
          :rules="[{ required: true }]"
          @click="show.showPicker = true"
        />
        
        
        
      <van-popup v-model="show.showPicker" position="bottom">
      <van-calendar
        v-model="show.showPicker"
        type="range"
        :allow-same-day="true"-------这个属性是允许将同一天作为开始和结束时间
        @cancel="show.showPicker = false"
        @confirm="onConfirmRange"
        :min-date="minDate"---------这里我是将最小选择时间规定为前三年,可根据需求来改写
      />
    </van-popup>
    
   
    computed: {
    minDate() {
      return new Date(Date.now() - 3 * 365 * 24 * 60 * 60 * 1000);
    },
  },
  
  
  
  
  methods:{
  // 点击弹出框的确定按钮之后的操作
     onConfirmRange(date) {
      const [start, end] = date;
      this.show.showPicker = false;
      // 根据自己需求写
      this.form.originStartTime = this.formatDate(start);
      this.form.originEndTime = this.formatDate(end);
      this.form.originTime = `${this.formatDate(start)}~${this.formatDate(end)}`;
    },
    
    // 格式化函数
      formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
  }