vant4日历选择日期区间并展示

375 阅读1分钟
效果

44.png

33.png

在utils文件夹下创建format_date.js文件
//需要先下载
import dayjs from "dayjs";
//计算今明日期
export function formatMonthDay(date) {
  return dayjs(date).format("MM月DD日");
}
//计算日期差
export function getDiffDate(startDate, endDate) {
  return dayjs(endDate).diff(startDate, "day");
}
使用
//js
import { formatMonthDay,getDiffDate } from "@/utils/format_date";
import { ref } from "vue";
// 获取今天startDate和明天endDate时间
const nowDate = new Date();
const newDate = new Date().setDate(nowDate.getDate() + 1);
//今天
const startDate = ref(formatMonthDay(nowDate));
//明天
const endDate = ref(formatMonthDay(newDate));
//日期差
const stayCount = ref(getDiffDate(nowDate, newDate));
const show = ref(false);
const onConfirm = (values) => {
  const [start, end] = values;
  show.value = false;
  startDate.value = formatMonthDay(start);
  endDate.value = formatMonthDay(end);
  stayCount.value = getDiffDate(start, end);
};
const formatter = (day) => {
  if (day.type === "start") {
    day.bottomInfo = "入住";
  } else if (day.type === "end") {
    day.bottomInfo = "离店";
  }
  return day;
};


//html
<div class="info-date public-margin" @click="show = true">
  <div class="date-enter">
    <div class="enter-text">入住</div>
    <div class="enter-time">{{ startDate }}</div>
  </div>
  <div class="date-total">共{{ stayCount }}晚</div>
  <div class="date-leave">
    <div class="enter-text">离店</div>
    <div class="enter-time">{{ endDate }}</div>
  </div>
</div>
<van-calendar
  color="var(--primary-color)"
  v-model:show="show"
  :formatter="formatter"
  type="range"
  @confirm="onConfirm"
/>


//css
.info-date {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.public-margin {
  margin-bottom: 1rem;
}