如何利用 computed 实现日历组件的日期逻辑计算?手把手封装教程
2026/4/20 2:03:14 网站建设 项目流程

computed 实现日历核心逻辑:自动推导当月天数、首日星期几及上下月占位日期,生成7×6日期网格;起始日由getDay()决定补位数,当月天数用new Date(year,month+1,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 API):const 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智能对话系统打造的智能语音助手解决方案

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询