经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue平铺日历组件之按住ctrl、shift键实现跨月、跨年多选日期的功能
来源:cnblogs  作者:豫见陈公子  时间:2023/5/25 9:07:54  对本文有异议

已经好久没有更新过博客了,大概有两三年了吧,因为换了工作,工作也比较忙,所以也就没有时间来写技术博客,期间也一直想写,但自己又比较懒,就给耽误了。今天这篇先续上,下一篇什么时候写,我也不知道,随心所欲、随遇而安、安之若素、素不相识也就无所谓了吧。

一开始看到这个功能需求,我也很懵逼,因为从来没有做过啊,哈哈。。。但转念一想既然产品能提出这个需求,想必会有人实现过,就去网上查了查资料,果不其然,还真有人做过,但离我想要的效果还是差着十万八千里,所以按照网上大神的思路,结合我司的实际需求,自己就把它给捣鼓出来了。

其实刚做好的效果还是能实现产品的需求的,我就让同事帮忙测试一下看看有没有什么bug,因为我司对bug的要求以及对用户体验的要求还是很严格的,所以在同事的实际测试以及提醒下,后面我又参照电脑上基于ctrl、shift键来选中文件的实际效果做了改进,算是不给测试提bug的机会吧。

照旧先上两张最后实现的效果图:


先来看看实现单月的日期组件calendar.vue

  1. <template>
  2. <div class="tiled-calendar">
  3. <div class="calendar-header">
  4. <span :class="getWeekClass(year)">{{monthCN[month]}}月</span>
  5. </div>
  6. <ul class="calendar-week">
  7. <li v-for="(item, index) in calendarWeek" :key="index" class="calendar-week-item" :class="getWeekClass(year, month + 1)">{{item}}</li>
  8. </ul>
  9. <ul class="calendar-body">
  10. <li v-for="(item, index) in calendar" :key="index" class="calendar-day" @click="onDay(item)">
  11. <template v-if="hasCurrentMonth">
  12. <span class="calendar-day-item" :class="getCellClass(item, index)">{{item.day}}</span>
  13. </template>
  14. <template v-else>
  15. <span class="calendar-day-item" :class="getCellClass(item, index)" v-if="isCurrentMonth(item.date)">{{item.day}}</span>
  16. </template>
  17. </li>
  18. </ul>
  19. </div>
  20. </template>
  21. <script>
  22. import dayjs from 'dayjs'
  23. import { mapState, mapMutations } from 'vuex'
  24. const monthCN = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二']
  25. const getNewDate = date => {
  26. const year = date.getFullYear()
  27. const month = date.getMonth()
  28. const day = date.getDate()
  29. return { year, month, day }
  30. }
  31. const getDate = (year, month, day) => new Date(year, month, day)
  32. export default {
  33. props: {
  34. year: {
  35. type: [String, Number],
  36. default: 2023
  37. },
  38. month: {
  39. type: [String, Number],
  40. default: 0
  41. },
  42. // 是否在当月日历中展示上个月和下个月的部分日期,默认不展示。
  43. hasCurrentMonth: {
  44. type: Boolean,
  45. default: false
  46. },
  47. // 休息日
  48. weekendList: Array,
  49. // 工作日
  50. workList: {
  51. type: Array,
  52. default: () => []
  53. },
  54. // 既非工作日也非休息日
  55. workRestOffList: Array
  56. },
  57. data () {
  58. return {
  59. calendarWeek: ['一', '二', '三', '四', '五', '六', '日'],
  60. today: dayjs().format('YYYYMMDD'),
  61. isCtrl: false,
  62. isShift: false,
  63. monthCN
  64. }
  65. },
  66. computed: {
  67. calendar () {
  68. const calendatArr = []
  69. const { year, month } = getNewDate(getDate(this.year, this.month, 1))
  70. const currentFirstDay = getDate(year, month, 1)
  71. // 获取当前月第一天星期几
  72. const weekDay = currentFirstDay.getDay()
  73. let startTime = null
  74. if (weekDay === 0) {
  75. // 当月第一天是星期天
  76. startTime = currentFirstDay - 6 * 24 * 60 * 60 * 1000
  77. } else {
  78. startTime = currentFirstDay - (weekDay - 1) * 24 * 60 * 60 * 1000
  79. }
  80. // 为了页面整齐排列 一并绘制42天
  81. for (let i = 0; i < 42; i++) {
  82. calendatArr.push({
  83. date: new Date(startTime + i * 24 * 60 * 60 * 1000),
  84. year: new Date(startTime + i * 24 * 60 * 60 * 1000).getFullYear(),
  85. month: new Date(startTime + i * 24 * 60 * 60 * 1000).getMonth() + 1,
  86. day: new Date(startTime + i * 24 * 60 * 60 * 1000).getDate()
  87. })
  88. }
  89. return calendatArr
  90. },
  91. ...mapState('d2admin', { selectedList: s => s.multiMarketCalendar.selectList })
  92. },
  93. mounted () {
  94. this.onKeyEvent()
  95. },
  96. methods: {
  97. ...mapMutations({ setSelectCalendar: 'd2admin/multiMarketCalendar/setSelectCalendar' }),
  98. onKeyEvent () {
  99. window.addEventListener('keydown', e => {
  100. const _e = e || window.event
  101. switch (_e.keyCode) {
  102. case 16:
  103. this.isShift = true
  104. break
  105. case 17:
  106. this.isCtrl = true
  107. break
  108. }
  109. })
  110. window.addEventListener('keyup', e => {
  111. const _e = e || window.event
  112. switch (_e.keyCode) {
  113. case 16:
  114. this.isShift = false
  115. break
  116. case 17:
  117. this.isCtrl = false
  118. break
  119. }
  120. })
  121. },
  122. // 是否是当前月
  123. isCurrentMonth (date) {
  124. const { year: currentYear, month: currentMonth } = getNewDate(getDate(this.year, this.month, 1))
  125. const { year, month } = getNewDate(date)
  126. return currentYear === year && currentMonth === month
  127. },
  128. onDay (item) {
  129. // 如果是同一年,当点击的月份小于当前系统日期的月份,则禁止点击。
  130. if (item.year === new Date().getFullYear() && item.month < new Date().getMonth() + 1) {
  131. return
  132. }
  133. // 如果是同一年又是同一个月,当点击的日期小于当前的日期,则禁止点击
  134. if (item.year === new Date().getFullYear() && item.month === new Date().getMonth() + 1 && item.day < new Date().getDate()) {
  135. return
  136. }
  137. // 如果点击的年份小月当前年份,则禁止点击。
  138. if (item.year < new Date().getFullYear()) {
  139. return
  140. }
  141. // 如果点击的日期不是那个月应有的日期(每个月的日期里边也会包含上个月和下个月的某几天日期,只是这些日期的颜色被置灰了),则禁止点击。
  142. if (!this.isCurrentMonth(item.date)) {
  143. return
  144. }
  145. const dateStr = dayjs(item.date).format('YYYYMMDD')
  146. const { isCtrl, isShift } = this
  147. // 按住ctrl
  148. if (isCtrl && !isShift) {
  149. this.setSelectCalendar({ dateStr, item, isCtrl })
  150. } else if (isCtrl && isShift) { // 同时按住ctrl和shift
  151. this.setSelectCalendar({ dateStr, item, isCtrl, isShift })
  152. } else if (isShift && !isCtrl) { // 按住shift
  153. this.setSelectCalendar({ dateStr, item, isShift })
  154. } else { // 不按ctrl和shift,一次只能选择一个
  155. this.setSelectCalendar({ dateStr, item })
  156. }
  157. },
  158. getWeekClass (year, month) {
  159. if (year < new Date().getFullYear()) return 'is-disabled'
  160. if (year === new Date().getFullYear() && month < new Date().getMonth() + 1) return 'is-disabled'
  161. },
  162. getCellClass (item, idx) {
  163. const { workList, weekendList, workRestOffList } = this
  164. const date = dayjs(item.date).format('YYYYMMDD')
  165. const today = `${item.year}${item.month < 10 ? '0' + item.month : item.month}${item.day < 10 ? '0' + item.day : item.day}`
  166. // 被选中的日期
  167. const index = this.selectedList.indexOf(date)
  168. if (index !== -1) {
  169. // 如果选中的日期是当年日期的周六周日,且这些日期不是工作日,则在选中时还是要保留它原来的红色字体,如果是工作日,则在选中时就不能再展示成红色字体了。
  170. if ((idx % 7 === 5 || idx % 7 === 6) && this.isCurrentMonth(item.date) && item.year >= new Date().getFullYear() && !(workList.length && workList.includes(date))) {
  171. return 'is-selected is-weekend'
  172. } else if (weekendList.length && weekendList.includes(date)) { // 休息日的选中(非周六周日的休息日)
  173. return 'is-selected is-weekend'
  174. } else if (workRestOffList.length && workRestOffList.includes(date)) { // 异常日期的选中
  175. return 'is-selected is-workRestOff'
  176. } else {
  177. return 'is-selected'
  178. }
  179. }
  180. // 默认显示当前日期
  181. if (today === this.today) {
  182. // 如果把当前日期也置为休息日,则也是要将当前日期标红
  183. if (weekendList.length && weekendList.includes(date)) {
  184. return 'is-today is-weekend'
  185. }
  186. // 异常日期
  187. if (workRestOffList.length && workRestOffList.includes(date)) {
  188. return 'is-today is-workRestOff'
  189. }
  190. return 'is-today'
  191. }
  192. // 如果日期不是那个月应有的日期(每个月的日期里边也会包含上个月和下个月的某几天日期,只是这些日期的颜色被置灰了),则禁止点击。
  193. // if (!this.isCurrentMonth(item.date)) {
  194. // return 'is-disabled'
  195. // }
  196. // 如果是同一年,当月份小于当前系统日期的月份,则禁止点击。
  197. if (item.year === new Date().getFullYear() && item.month < new Date().getMonth() + 1) {
  198. // 周六周日被设置成了工作日
  199. if ((idx % 7 === 5 || idx % 7 === 6) && (workList.length && workList.includes(date))) {
  200. return 'is-disabled is-work'
  201. }
  202. // 异常日期
  203. if (workRestOffList.length && workRestOffList.includes(date)) {
  204. return 'is-disabled is-workRestOff'
  205. }
  206. // 周六周日标红
  207. if (idx % 7 === 5 || idx % 7 === 6 || (weekendList.length && weekendList.includes(date))) {
  208. return 'is-disabled is-weekend'
  209. }
  210. return 'is-disabled'
  211. }
  212. // 如果是同一年又是同一个月,当日期小于当前的日期,则禁止点击
  213. if (item.year === new Date().getFullYear() && item.month === new Date().getMonth() + 1 && item.day < new Date().getDate()) {
  214. // 周六周日被设置成了工作日
  215. if ((idx % 7 === 5 || idx % 7 === 6) && (workList.length && workList.includes(date))) {
  216. return 'is-disabled is-work'
  217. }
  218. // 异常日期
  219. if (workRestOffList.length && workRestOffList.includes(date)) {
  220. return 'is-disabled is-workRestOff'
  221. }
  222. // 周六周日标红
  223. if (idx % 7 === 5 || idx % 7 === 6 || (weekendList.length && weekendList.includes(date))) {
  224. return 'is-disabled is-weekend'
  225. }
  226. return 'is-disabled'
  227. }
  228. // 如果年份小月当前年份,则禁止点击。
  229. if (item.year < new Date().getFullYear()) {
  230. // 周六周日被设置成了工作日
  231. if ((idx % 7 === 5 || idx % 7 === 6) && (workList.length && workList.includes(date))) {
  232. return 'is-disabled is-work'
  233. }
  234. // 异常日期
  235. if (workRestOffList.length && workRestOffList.includes(date)) {
  236. return 'is-disabled is-workRestOff'
  237. }
  238. // 周六周日标红
  239. if (idx % 7 === 5 || idx % 7 === 6 || (weekendList.length && weekendList.includes(date))) {
  240. return 'is-disabled is-weekend'
  241. }
  242. return 'is-disabled'
  243. }
  244. // 周六周日标红
  245. if ((idx % 7 === 5 || idx % 7 === 6) && this.isCurrentMonth(item.date) && item.year >= new Date().getFullYear()) {
  246. // 周六周日被设置成了工作日,则不标红
  247. if (workList.length && workList.includes(date)) {
  248. return 'is-work'
  249. }
  250. if (workRestOffList.length && workRestOffList.includes(date)) {
  251. return 'is-workRestOff'
  252. }
  253. return 'is-weekend'
  254. }
  255. // 休息日标红
  256. if (weekendList.length && weekendList.includes(date)) {
  257. return 'is-weekend'
  258. }
  259. // 既非工作日也非休息日
  260. if (workRestOffList.length && workRestOffList.includes(date)) {
  261. return 'is-workRestOff'
  262. }
  263. }
  264. },
  265. beforeDestroy() {
  266. window.removeEventListener('keydown')
  267. window.removeEventListener('keyup')
  268. }
  269. }
  270. </script>
  271. <style lang="scss" scoped>
  272. .calendar-header, .calendar-week{
  273. user-select: none;
  274. .is-disabled{
  275. cursor: not-allowed;
  276. opacity: 0.5;
  277. }
  278. }
  279. .tiled-calendar {
  280. height: 100%;
  281. box-sizing: border-box;
  282. margin: 0 20px 10px;
  283. font-size: 14px;
  284. ul, li{
  285. margin: 0;
  286. padding: 0;
  287. }
  288. .calendar-header {
  289. border-bottom: 1px solid #EDEEF1;
  290. padding: 8px 0;
  291. color: #1B1F26;
  292. text-align: center;
  293. margin-bottom: 8px;
  294. }
  295. .calendar-week {
  296. display: flex;
  297. height: 28px;
  298. line-height: 28px;
  299. border-right: none;
  300. border-left: none;
  301. margin-bottom: 2px;
  302. .calendar-week-item {
  303. list-style-type: none;
  304. width: 14.28%;
  305. text-align: center;
  306. color: #737985;
  307. }
  308. }
  309. .calendar-body {
  310. display: flex;
  311. flex-wrap: wrap;
  312. margin-top: 5px;
  313. .calendar-day {
  314. width: 14.28%;
  315. text-align: center;
  316. height: 34px;
  317. line-height: 34px;
  318. position: relative;
  319. display: flex;
  320. justify-content: center;
  321. align-items: center;
  322. .calendar-day-item {
  323. display: block;
  324. width: 26px;
  325. height: 26px;
  326. line-height: 26px;
  327. border-radius: 50%;
  328. cursor: pointer;
  329. user-select: none;
  330. color: #1B1F26;
  331. &:hover{
  332. background: rgba(69, 115, 243, .12);
  333. }
  334. }
  335. .is{
  336. &-today, &-selected{
  337. border: 1px solid #E60012;
  338. &:hover{
  339. background: rgba(69, 115, 243, .12);
  340. }
  341. }
  342. &-selected {
  343. border: 1px solid #4573F3;
  344. &:hover{
  345. background: none;
  346. }
  347. }
  348. &-disabled{
  349. cursor: not-allowed;
  350. color:#9E9E9E;
  351. &:hover{
  352. background: none;
  353. }
  354. }
  355. &-weekend{
  356. color: #E60012;
  357. }
  358. &-workRestOff{
  359. color: #FF7D00;
  360. }
  361. &-disabled{
  362. &.is-workRestOff{
  363. color: rgba(255, 125, 0, .4)
  364. }
  365. }
  366. &-disabled{
  367. &.is-weekend{
  368. color: rgba(230, 0, 18, .4)
  369. }
  370. }
  371. &-work{
  372. color: #1B1F26;
  373. }
  374. &-disabled.is-work{
  375. color: #9E9E9E
  376. }
  377. }
  378. }
  379. }
  380. }
  381. </style>

从以上也能看出,我们的需求还是很复杂的,比如,历史日期也就是所谓的过期的日期不能被选中,周六周日的日期要标红,还可以把工作日置为休息日,休息日置为工作日等等。这些功能说起来就一句话,可要实现出来,那可就属实太复杂了。

对了,在实现的过程中,我还使用到了vuex来保存点击选中的数据calendar.js:

  1. let selectList = []
  2. let shiftData = null
  3. let shiftDate = ''
  4. let currentSelect = []
  5. let lastSelect = []
  6. // 获取两个日期中间的所有日期
  7. const getBetweenDay = (starDay, endDay) => {
  8. var arr = []
  9. var dates = []
  10. // 设置两个日期UTC时间
  11. var db = new Date(starDay)
  12. var de = new Date(endDay)
  13. // 获取两个日期GTM时间
  14. var s = db.getTime() - 24 * 60 * 60 * 1000
  15. var d = de.getTime() - 24 * 60 * 60 * 1000
  16. // 获取到两个日期之间的每一天的毫秒数
  17. for (var i = s; i <= d;) {
  18. i = i + 24 * 60 * 60 * 1000
  19. arr.push(parseInt(i))
  20. }
  21. // 获取每一天的时间 YY-MM-DD
  22. for (var j in arr) {
  23. var time = new Date(arr[j])
  24. var year = time.getFullYear(time)
  25. var mouth = (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : ('0' + (time.getMonth() + 1))
  26. var day = time.getDate() >= 10 ? time.getDate() : ('0' + time.getDate())
  27. var YYMMDD = year + '' + mouth + '' + day
  28. dates.push(YYMMDD)
  29. }
  30. return dates
  31. }
  32. const shiftSelect = (dateStr, item) => {
  33. if (!shiftData) {
  34. shiftData = item.date
  35. shiftDate = `${item.year}-${item.month}-${item.day}`
  36. // 如果当前日期已选中,再次点击当前日期就取消选中。
  37. if (selectList.includes(dateStr)) {
  38. selectList.splice(selectList.indexOf(dateStr), 1)
  39. } else {
  40. selectList.push(dateStr)
  41. }
  42. } else {
  43. if (shiftData < item.date) {
  44. currentSelect = getBetweenDay(shiftDate, `${item.year}-${item.month}-${item.day}`)
  45. } else if (shiftData > item.date) {
  46. currentSelect = getBetweenDay(`${item.year}-${item.month}-${item.day}`, shiftDate)
  47. } else {
  48. currentSelect = [dateStr]
  49. }
  50. selectList = selectList.filter(item => !lastSelect.includes(item)) // 移除上次按shift复制的
  51. selectList = selectList.concat(currentSelect) // 添加本次按shift复制的
  52. lastSelect = currentSelect
  53. }
  54. }
  55. export default {
  56. namespaced: true,
  57. state: {
  58. selectList: []
  59. },
  60. mutations: {
  61. setSelectCalendar (s, { dateStr, item, isCtrl, isShift }) {
  62. // 按住ctrl
  63. if (isCtrl && !isShift) {
  64. // 如果当前日期已选中,再次点击当前日期就取消选中。
  65. if (selectList.includes(dateStr)) {
  66. selectList.splice(selectList.indexOf(dateStr), 1)
  67. } else {
  68. selectList.push(dateStr)
  69. }
  70. // 加上lastSelect = []这个就会在shift连续选了多个后,再按住ctrl键取消已选中的日期的中间的几个后,下次再按住
  71. // shift多选时,就会从按住ctrl取消选中的最后一个日期开始连续选择,但刚才取消已选中的那些日期
  72. // 之前的已经选中的日期依旧处于选中状态,与电脑自身的按住shift键多选的效果略有不同,所以要注释掉这串代码。
  73. // lastSelect = [] // 最开始这串代码是放开的
  74. } else if (isShift && !isCtrl) {
  75. // 加上selectList = []可以实现按住ctrl单选几个不连续的日期后,再按住shift键连选其他日期,就可以把之前
  76. // 按住ctrl键单选的其他日期都取消选中。不加selectList = []是可以在按住shift键连选其他日期时同时保留之前
  77. // 按住ctrl键单选的其他日期。
  78. selectList = [] // 最开始这串代码是没有的
  79. shiftSelect(dateStr, item)
  80. } else if (isCtrl && isShift) { // 同时按住ctrl和shift
  81. lastSelect = []
  82. shiftSelect(dateStr, item)
  83. } else { // 不按ctrl和shift,一次只能选择一个
  84. selectList = [dateStr]
  85. }
  86. if (!isShift) {
  87. shiftData = item.date
  88. shiftDate = `${item.year}-${item.month}-${item.day}`
  89. }
  90. selectList = [...new Set(selectList)].sort() // 去重、排序
  91. s.selectList = selectList
  92. },
  93. setSelectEmpty (s) {
  94. selectList = []
  95. shiftData = null
  96. shiftDate = ''
  97. currentSelect = []
  98. lastSelect = []
  99. s.selectList = []
  100. }
  101. }
  102. }

再来看看在以上单个日期组件的基础上实现1年12个月日历平铺的代码吧:

  1. <template>
  2. <div class="material-calendar-parent">
  3. <el-date-picker v-model="year" type="year" placeholder="选择年" @change="onChange" />
  4. <el-row :gutter="10">
  5. <el-col :span="6" v-for="(n, i) in 12" :key="i">
  6. <Calendar :year="year.getFullYear()" :month="i" :key="n" :workList="workList" :weekendList="weekendList" :workRestOffList="workRestOffList" />
  7. </el-col>
  8. </el-row>
  9. </div>
  10. </template>
  11. <script>
  12. import Calendar from './calendar'
  13. export default {
  14. components: { Calendar },
  15. data(){
  16. return {
  17. year: new Date(),
  18. workList: ['20220206', '20230107', '20230311'],
  19. weekendList: [{date: '20220118', market: '马来西亚,泰国'}, {date: '20230123', market: '中国澳门,韩国'}, {date: '20230213', market: '中国香港,美国'}, {date: '20230313', market: '中国台湾,法国'}],
  20. workRestOffList: ['20220101', '20220105', '20230101', '20230105', '20230218', '20230322', '20230330'],
  21. }
  22. },
  23. methods: {
  24. onChange(v){
  25. this.year = v
  26. }
  27. }
  28. }
  29. </script>
  30. <style lang="scss">
  31. .material-calendar-parent{
  32. .el-col{
  33. border-right: 1px solid #eee;
  34. border-bottom: 1px solid #eee;
  35. }
  36. }
  37. </style>

写到这里就不准备再往下写了,所有的代码都贴出来了。如果你想要的效果跟我的这个不太一样,你自己在这个基础上改吧改吧应该就可以用了。其实最关键的部分也就是那个按住ctrl、shift键实现跨月、跨年多选日期,理解了这个原理,其余的实现部分尽管复杂但并不难。

原文链接:https://www.cnblogs.com/tnnyang/p/17427873.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号