CalendarTable.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <template>
  2. <div class="calendar-table">
  3. <table>
  4. <thead>
  5. <tr>
  6. <th>日</th>
  7. <th>一</th>
  8. <th>二</th>
  9. <th>三</th>
  10. <th>四</th>
  11. <th>五</th>
  12. <th>六</th>
  13. </tr>
  14. </thead>
  15. <tbody>
  16. <!-- 填充的月份数据 -->
  17. <tr v-for="(week, weekIndex) in formattedCalendar" :key="weekIndex">
  18. <td v-for="(day, dayIndex) in week" :key="dayIndex" :class="{ 'event': day.event }">
  19. <span v-if="day.date !== null">{{ day.date }}</span>
  20. </td>
  21. </tr>
  22. </tbody>
  23. </table>
  24. </div>
  25. </template>
  26. <script>
  27. export default {
  28. name: 'CalendarTable',
  29. data() {
  30. // 起始和结束日期
  31. const startDate = new Date(2023, 7, 26); // 2023年8月26日,注意月份减1
  32. const endDate = new Date(2024, 1, 16); // 2024年2月16日,注意结束日期需加一天以包含该日
  33. // 初始化日期数组并填充起始日期前的空位以对齐星期
  34. let currentDate = new Date(startDate);
  35. currentDate.setDate(currentDate.getDate() - currentDate.getDay()); // 回退到当周的周一
  36. let calendarData = [];
  37. while (currentDate <= endDate) {
  38. calendarData.push(new Date(currentDate));
  39. currentDate.setDate(currentDate.getDate() + 1);
  40. }
  41. // 将日期分组到每周
  42. const weeks = [];
  43. for (let i = 0; i < calendarData.length; i += 7) {
  44. weeks.push(calendarData.slice(i, i + 7));
  45. }
  46. // 假设的事件数据,这里应根据实际需求添加
  47. const events = {
  48. '2023-08-26': '示例事件1', // 假定示例事件
  49. // ...其他事件
  50. '2024-02-16': '示例事件2' // 结束日期的事件
  51. };
  52. // 格式化日期并标记事件
  53. const formattedCalendar = weeks.map(week =>
  54. week.map(day => {
  55. const dateString = day.toISOString().split('T')[0];
  56. return {
  57. date: day.getDate(),
  58. event: events[dateString]
  59. };
  60. })
  61. );
  62. return {
  63. formattedCalendar
  64. };
  65. }
  66. };
  67. </script>
  68. <style scoped>
  69. .calendar-table {
  70. width: 100%;
  71. border-collapse: collapse;
  72. }
  73. .calendar-table th,
  74. .calendar-table td {
  75. border: 1px solid #ddd;
  76. padding: 4px;
  77. text-align: center;
  78. }
  79. .calendar-table th {
  80. background-color: #ccc;
  81. font-weight: bold;
  82. }
  83. .calendar-table td {
  84. height: 50px;
  85. width: 50px;
  86. padding: 13px;
  87. }
  88. .calendar-table tr:nth-child(even) td {
  89. background-color: #f8f8f8;
  90. }
  91. .calendar-table .event {
  92. font-weight: bold;
  93. color: purple;
  94. }
  95. .calendar-table td span {
  96. display: block;
  97. text-align: left;
  98. margin-left: 5px;
  99. }
  100. </style>