vant Calendar组件,显示单个月份,可切换月份,展开与收起显示日期功能

'# vant Calendar组件,显示单个月份,可切换月份,展开与收起显示日期功能

一、背景与问题

在开发基于移动端的业务系统时,日期选择是常见的需求。传统开发中,开发者需要手动实现日期计算、日历渲染、月份切换等复杂逻辑。Vant 的 Calendar 组件提供了开箱即用的解决方案,但其底层实现机制值得深入研究。

在实际项目中,我们可能需要:

  1. 展示单个月份的日历
  2. 支持月份切换
  3. 支持展开/收起日期显示
  4. 自定义日期格式
  5. 高性能渲染

但开发过程中容易遇到:

  • 月份切换时日期计算错误
  • 展开/收起时布局错乱
  • 多选/范围选择逻辑混乱
  • 移动端适配问题
  • 性能瓶颈

二、基本原理

Vant Calendar 的核心实现包含以下技术要素:

1. 日期计算系统

通过 dayjsmoment 等库处理时间戳转换,计算:

  • 当前月份的起始日
  • 当前月份的天数
  • 当前月份的星期几
  • 每个日期的特殊标记(如今天、周末)
// 计算当前月份的日期数据
function getMonthDays(year, month) {
  const date = new Date(year, month, 1);
  const days = [];
  const firstDay = date.getDay(); // 获取周几(0-6)
  
  // 填充上个月的空白日期
  for (let i = firstDay - 1; i >= 0; i--) {
    days.push({
      date: new Date(year, month - 1, 32 - i),
      disabled: true
    });
  }
  
  // 填充当前月的日期
  for (let i = 1; i <= new Date(year, month + 1, 0).getDate(); i++) {
    days.push({
      date: new Date(year, month, i),
      disabled: false
    });
  }
  
  // 填充下个月的空白日期
  const lastDay = new Date(year, month + 1, 0).getDate();
  for (let i = 1; i <= 6 - (lastDay - 1) % 7; i++) {
    days.push({
      date: new Date(year, month + 1, i),
      disabled: true
    });
  }
  
  return days;
}

2. 月份切换逻辑

通过维护当前年份和月份的状态,实现月份切换:

// 切换月份
const prevMonth = () => {
  if (currentMonth === 0) {
    setCurrentMonth(11);
    setCurrentYear(currentYear - 1);
  } else {
    setCurrentMonth(currentMonth - 1);
  }
};

const nextMonth = () => {
  if (currentMonth === 11) {
    setCurrentMonth(0);
    setCurrentYear(currentYear + 1);
  } else {
    setCurrentMonth(currentMonth + 1);
  }
};

3. 展开/收起状态管理

通过布尔状态控制日历的展开/收起状态:

const [isExpanded, setIsExpanded] = useState(false);

三、环境准备

npm install vant

项目结构建议:

src/
├── components/
│   └── Calendar/
│       ├── index.vue
│       ├── styles.scss
│       └── utils.js
├── pages/
│   └── calendar/
│       └── index.vue
├── assets/
├── services/
├── utils/
└── App.vue

四、核心实现

1. 基础日历组件实现

<template>
  <div class="calendar-container">
    <div class="month-header">
      <div class="month-name">{{ `${currentYear}年${currentMonth + 1}月` }}</div>
      <div class="month-controls">
        <button @click="prevMonth">上月</button>
        <button @click="nextMonth">下月</button>
      </div>
    </div>
    <div class="calendar-grid">
      <div class="week-day" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
        {{ day }}
      </div>
      <div 
        v-for="day in getMonthDays(currentYear, currentMonth)" 
        :key="day.date.getTime()"
        class="calendar-day"
        :class="{
          'current-day': isToday(day.date),
          'disabled-day': day.disabled,
          'selected-day': isSelected(day.date)
        }"
        @click="selectDate(day.date)"
      >
        <div class="day-number">{{ day.date.getDate() }}</div>
        <div class="day-label" v-if="isSpecialDay(day.date)">*</div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import dayjs from 'dayjs';

export default {
  setup() {
    const currentYear = ref(2023);
    const currentMonth = ref(8); // 从0开始计数
    const isExpanded = ref(false);
    
    const getMonthDays = (year, month) => {
      // 实现如前所述的日期计算逻辑
    };
    
    const isToday = (date) => {
      return dayjs().isSame(date, 'day');
    };
    
    const isSelected = (date) => {
      // 实现选中日期的判断逻辑
    };
    
    const selectDate = (date) => {
      // 实现日期选择逻辑
    };
    
    const prevMonth = () => {
      // 实现上月切换逻辑
    };
    
    const nextMonth = () => {
      // 实现下月切换逻辑
    };
    
    return {
      currentYear,
      currentMonth,
      isExpanded,
      getMonthDays,
      isToday,
      isSelected,
      selectDate,
      prevMonth,
      nextMonth
    };
  }
};
</script>

<style scoped>
.calendar-container {
  width: 100%;
  max-width: 375px;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  overflow: hidden;
}

.month-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.month-name {
  font-size: 16px;
  font-weight: 500;
}

.month-controls button {
  padding: 6px 12px;
  border: none;
  background: #f0f0f0;
  border-radius: 4px;
  cursor: pointer;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  padding: 8px;
}

.week-day {
  text-align: center;
  font-weight: bold;
  color: #999;
}

.calendar-day {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
}

.calendar-day.current-day {
  background-color: #f0f0f0;
}

.calendar-day.disabled-day {
  color: #ccc;
  opacity: 0.5;
}

.calendar-day.selected-day {
  background-color: #4CAF50;
  color: #fff;
}
</style>

2. 展开/收起功能实现

<template>
  <div class="calendar-container">
    <div class="month-header">
      <div class="month-name">{{ `${currentYear}年${currentMonth + 1}月` }}</div>
      <div class="month-controls">
        <button @click="prevMonth">上月</button>
        <button @click="nextMonth">下月</button>
      </div>
    </div>
    <div class="calendar-grid">
      <div class="week-day" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
        {{ day }}
      </div>
      <div 
        v-for="day in getMonthDays(currentYear, currentMonth)" 
        :key="day.date.getTime()"
        class="calendar-day"
        :class="{
          'current-day': isToday(day.date),
          'disabled-day': day.disabled,
          'selected-day': isSelected(day.date)
        }"
        @click="selectDate(day.date)"
      >
        <div class="day-number">{{ day.date.getDate() }}</div>
        <div class="day-label" v-if="isSpecialDay(day.date)">*</div>
      </div>
    </div>
    <div class="expand-control" @click="toggleExpand">
      {{ isExpanded ? '收起' : '展开' }}日期
    </div>
  </div>
</template>

<script>
export default {
  // 同上
  methods: {
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
    }
  }
};
</script>

<style scoped>
.expand-control {
  padding: 12px 16px;
  text-align: center;
  cursor: pointer;
  background-color: #f5f5f5;
}
</style>

3. 日期选择功能实现

<template>
  <div class="calendar-container">
    <div class="month-header">
      <div class="month-name">{{ `${currentYear}年${currentMonth + 1}月` }}</div>
      <div class="month-controls">
        <button @click="prevMonth">上月</button>
        <button @click="nextMonth">下月</button>
      </div>
    </div>
    <div class="calendar-grid">
      <div class="week-day" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
        {{ day }}
      </div>
      <div 
        v-for="day in getMonthDays(currentYear, currentMonth)" 
        :key="day.date.getTime()"
        class="calendar-day"
        :class="{
          'current-day': isToday(day.date),
          'disabled-day': day.disabled,
          'selected-day': isSelected(day.date)
        }"
        @click="selectDate(day.date)"
      >
        <div class="day-number">{{ day.date.getDate() }}</div>
        <div class="day-label" v-if="isSpecialDay(day.date)">*</div>
      </div>
    </div>
    <div class="selected-dates">
      <div v-for="date in selectedDates" :key="date.getTime()">
        {{ date.toLocaleDateString() }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  // 同上
  data() {
    return {
      selectedDates: []
    };
  },
  methods: {
    selectDate(date) {
      const index = this.selectedDates.findIndex(d => d.getTime() === date.getTime());
      if (index === -1) {
        this.selectedDates.push(date);
      } else {
        this.selectedDates.splice(index, 1);
      }
    }
  }
};
</script>

五、完整案例

1. 项目结构

src/
├── components/
│   └── Calendar/
│       ├── index.vue
│       └── styles.scss
├── pages/
│   └── calendar/
│       └── index.vue
├── assets/
├── services/
├── utils/
└── App.vue

2. 完整代码示例

<template>
  <div class="calendar-demo">
    <div class="calendar-wrapper">
      <Calendar 
        :current-year="currentYear"
        :current-month="currentMonth"
        :is-expanded="isExpanded"
        @select-date="handleSelectDate"
      />
    </div>
    <div class="selected-dates">
      <h3>已选日期</h3>
      <ul>
        <li v-for="date in selectedDates" :key="date.getTime()">
          {{ date.toLocaleDateString() }}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Calendar from '@/components/Calendar/index.vue';

export default {
  components: {
    Calendar
  },
  data() {
    return {
      currentYear: 2023,
      currentMonth: 8, // 从0开始计数
      isExpanded: false,
      selectedDates: []
    };
  },
  methods: {
    handleSelectDate(date) {
      const index = this.selectedDates.findIndex(d => d.getTime() === date.getTime());
      if (index === -1) {
        this.selectedDates.push(date);
      } else {
        this.selectedDates.splice(index, 1);
      }
    }
  }
};
</script>

<style scoped>
.calendar-demo {
  padding: 20px;
}

.calendar-wrapper {
  margin-bottom: 20px;
}
</style>

六、源码解析

1. 日期计算核心逻辑

function getMonthDays(year, month) {
  const date = new Date(year, month, 1);
  const days = [];
  const firstDay = date.getDay(); // 获取周几(0-6)
  
  // 填充上个月的空白日期
  for (let i = firstDay - 1; i >= 0; i--) {
    days.push({
      date: new Date(year, month - 1, 32 - i),
      disabled: true
    });
  }
  
  // 填充当前月的日期
  for (let i = 1; i <= new Date(year, month + 1, 0).getDate(); i++) {
    days.push({
      date: new Date(year, month, i),
      disabled: false
    });
  }
  
  // 填充下个月的空白日期
  const lastDay = new Date(year, month + 1, 0).getDate();
  for (let i = 1; i <= 6 - (lastDay - 1) % 7; i++) {
    days.push({
      date: new Date(year, month + 1, i),
      disabled: true
    });
  }
  
  return days;
}

2. 月份切换逻辑

const prevMonth = () => {
  if (currentMonth === 0) {
    currentYear--;
    currentMonth = 11;
  } else {
    currentMonth--;
  }
};

const nextMonth = () => {
  if (currentMonth === 11) {
    currentYear++;
    currentMonth = 0;
  } else {
    currentMonth++;
  }
};

3. 展开/收起状态管理

toggleExpand() {
  this.isExpanded = !this.isExpanded;
}

七、进阶使用

1. 多日期选择扩展

<template>
  <div class="calendar-container">
    <div class="month-header">
      <div class="month-name">{{ `${currentYear}年${currentMonth + 1}月` }}</div>
      <div class="month-controls">
        <button @click="prevMonth">上月</button>
        <button @click="nextMonth">下月</button>
      </div>
    </div>
    <div class="calendar-grid">
      <div class="week-day" v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
        {{ day }}
      </div>
      <div 
        v-for="day in getMonthDays(currentYear, currentMonth)" 
        :key="day.date.getTime()"
        class="calendar-day"
        :class="{
          'current-day': isToday(day.date),
          'disabled-day': day.disabled,
          'selected-day': isSelected(day.date)
        }"
        @click="selectDate(day.date)"
      >
        <div class="day-number">{{ day.date.getDate() }}</div>
        <div class="day-label" v-if="isSpecialDay(day.date)">*</div>
      </div>
    </div>
    <div class="selected-dates">
      <h3>已选日期</h3>
      <ul>
        <li v-for="date in selectedDates" :key="date.getTime()">
          {{ date.toLocaleDateString() }}
        </li>
      </ul>
    </div>
  </div>
</template>

2. 日期格式化

import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn.js';

dayjs.locale('zh-cn');

3. 日期范围选择

selectDate(date) {
  if (this.selectedDates.length === 0) {
    this.selectedDates.push(date);
  } else if (this.selectedDates.length === 1) {
    const start = this.selectedDates[0];
    const end = date;
    if (dayjs(start).isSame(dayjs(end), 'month')) {
      this.selectedDates = [];
    } else {
      this.selectedDates.push(date);
    }
  } else {
    this.selectedDates = [];
  }
}

八、性能与工程实践

1. 性能优化方案

  1. 虚拟滚动:对于需要展示长日期列表的场景,使用vue-virtual-scroll-list
  2. 防抖处理:对频繁触发的事件进行防抖处理
  3. 懒加载:仅在需要时计算日期数据
  4. 数据缓存:缓存已经计算过的月份数据

2. 异常处理

try {
  const date = new Date(year, month, 1);
  if (isNaN(date.getTime())) {
    throw new Error('无效的日期');
  }
} catch (e) {
  console.error('日期计算错误:', e);
}

3. 安全考虑

  1. 输入验证:对用户输入的日期进行严格校验
  2. XSS 防护:对用户输入的内容进行转义处理
  3. 权限控制:对敏感日期操作进行权限校验

九、常见问题与踩坑

1. 月份切换时日期计算错误

问题现象:切换月份时,日历显示的日期不正确

解决方案

  • 确认月份是从0开始还是从1开始计数
  • 检查new Date(year, month + 1, 0)是否正确计算了月末日期
  • 确认是否考虑了闰年等特殊日期

2. 展开/收起时布局错乱

问题现象:展开/收起时日期显示错位

解决方案

  • 使用transition实现平滑过渡
  • 确保容器高度计算正确
  • 使用flex-shrink控制元素收缩

3. 多选日期逻辑混乱

问题现象:多选日期时选择范围不正确

解决方案

  • 使用dayjs库处理日期比较
  • 避免直接操作DOM节点
  • 使用状态管理库维护选择状态

十、最佳实践

1. 推荐使用场景

  1. 移动端日期选择:适配移动端屏幕尺寸
  2. 单个月份展示:需要精确控制显示的月份
  3. 日历插件开发:需要自定义日历功能
  4. 日期范围选择:需要支持多日期选择

2. 不推荐使用场景

  1. 需要支持年份切换:需要更复杂的日期计算
  2. 需要支持农历/节气:需要额外的计算逻辑
  3. 需要支持复杂日期范围:如周、月、季度等
  4. 需要支持多语言:需要额外的国际化处理

十一、总结

Vant 的 Calendar 组件提供了完善的日期选择功能,但其底层实现涉及日期计算、状态管理、布局控制等多个技术点。通过深入理解其工作原理,我们可以更好地利用其功能,同时避免常见错误。

在实际开发中,我们需要注意:

  • 正确处理月份切换逻辑
  • 确保展开/收起状态的平滑过渡
  • 处理多选日期的复杂逻辑
  • 考虑性能优化方案
  • 遵循安全最佳实践

通过合理使用 Vant 的 Calendar 组件,我们可以快速实现日期选择功能,同时确保代码的可维护性和可扩展性。在遇到特殊需求时,可以根据项目实际情况进行定制开发,实现更复杂的功能需求。

none
最后修改于:2026年09月24日 05:46

评论已关闭

推荐阅读

AIGC实战——Transformer模型
2024年12月01日
Socket TCP 和 UDP 编程基础(Python)
2024年11月30日
python , tcp , udp
如何使用 ChatGPT 进行学术润色?你需要这些指令
2024年12月01日
AI
最新 Python 调用 OpenAi 详细教程实现问答、图像合成、图像理解、语音合成、语音识别(详细教程)
2024年11月24日
ChatGPT 和 DALL·E 2 配合生成故事绘本
2024年12月01日
omegaconf,一个超强的 Python 库!
2024年11月24日
【视觉AIGC识别】误差特征、人脸伪造检测、其他类型假图检测
2024年12月01日
[超级详细]如何在深度学习训练模型过程中使用 GPU 加速
2024年11月29日
Python 物理引擎pymunk最完整教程
2024年11月27日
MediaPipe 人体姿态与手指关键点检测教程
2024年11月27日
深入了解 Taipy:Python 打造 Web 应用的全面教程
2024年11月26日
基于Transformer的时间序列预测模型
2024年11月25日
Python在金融大数据分析中的AI应用(股价分析、量化交易)实战
2024年11月25日
AIGC Gradio系列学习教程之Components
2024年12月01日
Python3 `asyncio` — 异步 I/O,事件循环和并发工具
2024年11月30日
llama-factory SFT系列教程:大模型在自定义数据集 LoRA 训练与部署
2024年12月01日
Python 多线程和多进程用法
2024年11月24日
Python socket详解,全网最全教程
2024年11月27日
python之plot()和subplot()画图
2024年11月26日
理解 DALL·E 2、Stable Diffusion 和 Midjourney 工作原理
2024年12月01日