|
| 1 | +# Vue3.x 封装一个简单的日历 |
| 2 | + |
| 3 | +- 技术栈 |
| 4 | + |
| 5 | +`Vue3.x` + `Vite` |
| 6 | + |
| 7 | +## 效果 |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +## 初始化一个基于 Vue.3x 的 demo |
| 12 | + |
| 13 | +```sh |
| 14 | +npm create vite@latest |
| 15 | + |
| 16 | +npm i less -D |
| 17 | +``` |
| 18 | + |
| 19 | +图 |
| 20 | + |
| 21 | +## 开发组件 |
| 22 | + |
| 23 | +- 展示为 6\*7 的布局 |
| 24 | +- 6 行 7 列 |
| 25 | + |
| 26 | +### 获取指定时间或者当前时间的年,月,日 |
| 27 | + |
| 28 | +```js |
| 29 | +const date = modelValue.value ? new Date(modelValue.value) : new Date() |
| 30 | +const [y, m, d] = [date.getFullYear(), date.getMonth() + 1, date.getDate()] |
| 31 | +``` |
| 32 | + |
| 33 | +### 获取当月开始星期用于计算前面填充时间 |
| 34 | + |
| 35 | +```js |
| 36 | +const curDays = [] |
| 37 | +/** |
| 38 | + * 当月开始星期 |
| 39 | + */ |
| 40 | +const startW = new Date(y, m, 1).getDay() |
| 41 | +let nm = m - 1 |
| 42 | +let ny = y |
| 43 | +if (nm === 0) { |
| 44 | + nm = 12 |
| 45 | + ny-- |
| 46 | +} |
| 47 | +/** |
| 48 | + * 上月总天数 |
| 49 | + */ |
| 50 | +const prevTotalDay = getMonthDay(ny, nm) |
| 51 | +Array.from({ length: startW }, (_, i) => { |
| 52 | + const newDay = prevTotalDay - i |
| 53 | + const tempDate = `${ny}-${nm}-${newDay}` |
| 54 | + curDays.push({ y: ny, m: nm, d: newDay, value: addZero(newDay), disabled: true, today: tempDate === nowDate }) |
| 55 | +}) |
| 56 | +``` |
| 57 | + |
| 58 | +### 填充当月总天数 |
| 59 | + |
| 60 | +```js |
| 61 | +/** |
| 62 | + * 当月总天数 |
| 63 | + */ |
| 64 | +const totalDay = getMonthDay(y, m) |
| 65 | +Array.from({ length: totalDay }, (_, i) => { |
| 66 | + const nd = i + 1 |
| 67 | + const tempDate = `${y}-${addZero(m)}-${addZero(nd)}` |
| 68 | + const today = tempDate === nowDate |
| 69 | + const selected = modelValue.value ? tempDate === modelValue.value : false |
| 70 | + curDays.push({ y, m, d: nd, value: addZero(nd), today, selected }) |
| 71 | +}) |
| 72 | +``` |
| 73 | + |
| 74 | +### 计算后面的填充时间 |
| 75 | + |
| 76 | +```js |
| 77 | +/** |
| 78 | + * 下月 |
| 79 | + */ |
| 80 | +let nextM = m + 1 |
| 81 | +let nextY = y |
| 82 | +if (nextM > 12) { |
| 83 | + nextM = 1 |
| 84 | + nextY++ |
| 85 | +} |
| 86 | +Array.from({ length: total - curDays.length }, (_, i) => { |
| 87 | + const nd = i + 1 |
| 88 | + const tempDate = `${nextY}-${nextM}-${nd}` |
| 89 | + curDays.push({ y: nextY, m: nextM, d: nd, value: addZero(nd), disabled: true, today: tempDate === nowDate }) |
| 90 | +}) |
| 91 | +``` |
| 92 | + |
| 93 | +## 总结 |
| 94 | + |
| 95 | +- 这样6\*7的数据计算完成 |
| 96 | +- 把这个计算封装一个方法,然后切换月和切换年时调用这个方法,这样日历就封装完成 |
| 97 | +- [演示地址](https://mineh5ui.biaov.cn/v2/doc/calendar) |
| 98 | +- [源码地址](https://github.com/biaov/m-simple-calendar) |
0 commit comments