如何利用 computed 实现日历组件的日期逻辑计算?手把手封装教程

张开发
2026/4/20 2:03:18 15 分钟阅读

分享文章

如何利用 computed 实现日历组件的日期逻辑计算?手把手封装教程
computed 实现日历核心逻辑自动推导当月天数、首日星期几及上下月占位日期生成7×6日期网格起始日由getDay()决定补位数当月天数用new Date(year,month1,0).getDate()获取总格子固定42个。用 computed 实现日历组件的日期逻辑核心是把“当前月有多少天”“第一天星期几”“上月/下月需要补的占位日期”这些动态值交给 Vue 的响应式系统自动推导——不用手动写一堆 methods 或 watch数据一变视图立刻更新。计算当月日期网格7×6 表格日历本质是一个 7 列 × 最多 6 行的二维数组。关键不是渲染今天而是算出整个可视区域该显示哪些日期起始日当月 1 号是星期几new Date(year, month, 1).getDay()决定前面要补几个上月日期当月天数用 new Date(year, month 1, 0).getDate() 获取比如 2024-02 的下月是 3 月3 月 0 日就是 2 月最后一天总格子数固定 42 个6 行 × 7 列不足就用上月/下月日期补全代码示例Vue 3 Composition APIconst calendarDays computed(() {??const firstDay new Date(props.year, props.month, 1).getDay(); // 0~6??const daysInMonth new Date(props.year, props.month 1, 0).getDate();??const prevMonthDays new Date(props.year, props.month, 0).getDate();??const days [];??// 上月补位??for (let i firstDay - 1; i 0; i--) {????days.push({ date: new Date(props.year, props.month - 1, prevMonthDays - i), isCurrentMonth: false });??}??// 当月主体??for (let i 1; i ????days.push({ date: new Date(props.year, props.month, i), isCurrentMonth: true });??}??// 下月补位补满 42 个??const remaining 42 - days.length;??for (let i 1; i ????days.push({ date: new Date(props.year, props.month 1, i), isCurrentMonth: false });??}??return days;});自动识别今天、选中日、范围高亮这些状态不需额外监听直接在 computed 里比对即可是否为今天用 date.toDateString() new Date().toDateString()是否被选中对比 date 和响应式变量 selectedDate同样用 toDateString() 避免时分秒干扰是否在日期范围内如双日历选择区间检查 date 是否介于 rangeStart 和 rangeEnd 之间注意边界处理把这些判断内联进 calendarDays 的每个 item 里模板中直接绑定 class 腾讯小微 基于微信AI智能对话系统打造的智能语音助手解决方案

更多文章