Skip to content

Vue3.x 封装一个简单的日历

  • 技术栈

Vue3.x + Vite

效果

效果图

初始化一个基于 Vue.3x 的 demo

sh
npm create vite@latest

npm i less -D

开发组件

  • 展示为 6*7 的布局
  • 6 行 7 列

获取指定时间或者当前时间的年,月,日

js
const date = modelValue.value ? new Date(modelValue.value) : new Date()
const [y, m, d] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]

获取当月开始星期用于计算前面填充时间

js
const curDays = []
/**
 * 当月开始星期
 */
const startW = new Date(`${y}-${m}-1`).getDay()
let nm = m - 1
let ny = y
if (nm === 0) {
  nm = 12
  ny--
}
/**
 * 上月总天数
 */
const prevTotalDay = getMonthDay(ny, nm)
Array.from({ length: startW }, (_, i) => {
  const newDay = prevTotalDay - i
  const tempDate = `${ny}-${nm}-${newDay}`
  curDays.push({ y: ny, m: nm, d: newDay, value: addZero(newDay), disabled: true, today: tempDate === nowDate })
})

填充当月总天数

js
/**
 * 当月总天数
 */
const totalDay = getMonthDay(y, m)
Array.from({ length: totalDay }, (_, i) => {
  const nd = i + 1
  const tempDate = `${y}-${addZero(m)}-${addZero(nd)}`
  const today = tempDate === nowDate
  const selected = modelValue.value ? tempDate === modelValue.value : false
  curDays.push({ y, m, d: nd, value: addZero(nd), today, selected })
})

计算后面的填充时间

js
/**
 * 下月
 */
let nextM = m + 1
let nextY = y
if (nextM > 12) {
  nextM = 1
  nextY++
}
Array.from({ length: total - curDays.length }, (_, i) => {
  const nd = i + 1
  const tempDate = `${nextY}-${nextM}-${nd}`
  curDays.push({ y: nextY, m: nextM, d: nd, value: addZero(nd), disabled: true, today: tempDate === nowDate })
})

总结

  • 这样6*7的数据计算完成
  • 把这个计算封装一个方法,然后切换月和切换年时调用这个方法,这样日历就封装完成
  • 演示地址
  • 源码地址,支持平台:
    • Vue3.x
    • Vue2.x
    • 微信小程序

基于 MIT 许可发布