修改Vue+Moment+CSS Grid日历为周一首日并修复月份切换问题
修复方案
你需要修改3处核心代码即可实现周一为周首的日历,同时解决月份切换错误问题:
1. 修改HTML星期表头顺序
将原来周日开头的表头调整为周一开头,调整后的代码如下:
<div class="weekday">M</div> <div class="weekday">T</div> <div class="weekday">W</div> <div class="weekday">T</div> <div class="weekday">F</div> <div class="weekday">S</div> <div class="weekday">S</div>
2. 修正JS的列偏移计算逻辑
Moment.js的day()方法返回值是0=周日、1=周一、...、6=周六,你需要根据周一为周首的规则重新计算第一个日期的网格列位置,同时避免直接修改原始date对象导致的月份切换异常:
const calendar = new Vue({ el: '#app', data() { return { date: moment(), days: [], monthName: '', } }, methods: { column(index) { if (index == 0) { const firstDayOfMonth = this.days[0].day() // 周日对应第7列,其余星期直接返回day()值作为列号 return firstDayOfMonth === 0 ? 7 : firstDayOfMonth } }, isToday(day) { return moment().isSame(day, 'day') }, updateMonth(){ this.monthName = this.date.format("MMMM YYYY") // 新增clone(),避免修改原始date对象的状态 let monthDate = this.date.clone().startOf('month'); this.days = [...Array(monthDate.daysInMonth())].map((_, i) => monthDate.clone().add(i, 'day')) }, nextMonth(){ this.date.add(1,'month') this.updateMonth() }, previousMonth(){ this.date.subtract(1,'month') this.updateMonth() }, }, mounted() { this.updateMonth() } })
3. CSS无需修改grid-template-columns配置
你原来的7列网格配置完全适配,不需要做任何调整。
错误原因说明
你之前两种方案的问题分别是:
- 第一种直接减2的硬编码偏移仅对8月生效,没有适配不同月份第一天的星期差异
- 第二种硬写死
grid-column:7仅对第一天为周日的月份生效,切换到其他月份自然排布错误
内容的提问来源于stack exchange,提问作者moogeek
相关产品推荐
相关产品推荐

