网站建设网站的好处seo的外链平台有哪些
Vue3.x 封装一个简单的日历
- 技术栈
Vue3.x
+ Vite
效果
初始化一个基于 Vue.3x 的 demo
npm create vite@latestnpm i less -D
开发组件
- 展示为 6*7 的布局
- 6 行 7 列
获取指定时间或者当前时间的年,月,日
const date = modelValue.value ? new Date(modelValue.value) : new Date()
const [y, m, d] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
获取当月开始星期用于计算前面填充时间
const curDays = []
/*** 当月开始星期*/
const startW = new Date(y, m, 1).getDay()
let nm = m - 1
let ny = y
if (nm === 0) {nm = 12ny--
}
/*** 上月总天数*/
const prevTotalDay = getMonthDay(ny, nm)
Array.from({ length: startW }, (_, i) => {const newDay = prevTotalDay - iconst tempDate = `${ny}-${nm}-${newDay}`curDays.push({ y: ny, m: nm, d: newDay, value: addZero(newDay), disabled: true, today: tempDate === nowDate })
})
填充当月总天数
/*** 当月总天数*/
const totalDay = getMonthDay(y, m)
Array.from({ length: totalDay }, (_, i) => {const nd = i + 1const tempDate = `${y}-${addZero(m)}-${addZero(nd)}`const today = tempDate === nowDateconst selected = modelValue.value ? tempDate === modelValue.value : falsecurDays.push({ y, m, d: nd, value: addZero(nd), today, selected })
})
计算后面的填充时间
/*** 下月*/
let nextM = m + 1
let nextY = y
if (nextM > 12) {nextM = 1nextY++
}
Array.from({ length: total - curDays.length }, (_, i) => {const nd = i + 1const 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
微信小程序