cl-calendar.uvue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. <template>
  2. <view class="cl-calendar" :class="[pt.className]">
  3. <!-- 年月选择器弹窗 -->
  4. <calendar-picker
  5. :year="currentYear"
  6. :month="currentMonth"
  7. :ref="refs.set('picker')"
  8. @change="onYearMonthChange"
  9. ></calendar-picker>
  10. <!-- 头部导航栏 -->
  11. <view class="cl-calendar__header" v-if="showHeader">
  12. <!-- 上一月按钮 -->
  13. <view
  14. class="cl-calendar__header-prev"
  15. :class="{ 'is-dark': isDark }"
  16. @tap.stop="gotoPrevMonth"
  17. >
  18. <cl-icon name="arrow-left-s-line"></cl-icon>
  19. </view>
  20. <!-- 当前年月显示区域 -->
  21. <view class="cl-calendar__header-date" @tap="refs.open('picker')">
  22. <slot name="current-date">
  23. <cl-text :pt="{ className: 'text-lg' }">{{
  24. $t(`{year}年{month}月`, { year: currentYear, month: currentMonth })
  25. }}</cl-text>
  26. </slot>
  27. </view>
  28. <!-- 下一月按钮 -->
  29. <view
  30. class="cl-calendar__header-next"
  31. :class="{ 'is-dark': isDark }"
  32. @tap.stop="gotoNextMonth"
  33. >
  34. <cl-icon name="arrow-right-s-line"></cl-icon>
  35. </view>
  36. </view>
  37. <!-- 星期标题行 -->
  38. <view class="cl-calendar__weeks" :style="{ gap: `${cellGap}px` }" v-if="showWeeks">
  39. <view class="cl-calendar__weeks-item" v-for="weekName in weekLabels" :key="weekName">
  40. <cl-text>{{ weekName }}</cl-text>
  41. </view>
  42. </view>
  43. <!-- 日期网格容器 -->
  44. <view
  45. class="cl-calendar__view"
  46. ref="viewRef"
  47. :style="{ height: `${viewHeight}px`, gap: `${cellGap}px` }"
  48. @tap="onTap"
  49. >
  50. <!-- #ifndef APP -->
  51. <view
  52. class="cl-calendar__view-row"
  53. :style="{ gap: `${cellGap}px` }"
  54. v-for="(weekRow, rowIndex) in dateMatrix"
  55. :key="rowIndex"
  56. >
  57. <view
  58. class="cl-calendar__view-cell"
  59. v-for="(dateCell, cellIndex) in weekRow"
  60. :key="cellIndex"
  61. :class="{
  62. 'is-selected': dateCell.isSelected,
  63. 'is-range': dateCell.isRange,
  64. 'is-hide': dateCell.isHide,
  65. 'is-disabled': dateCell.isDisabled,
  66. 'is-today': dateCell.isToday,
  67. 'is-other-month': !dateCell.isCurrentMonth
  68. }"
  69. :style="{
  70. height: cellHeight + 'px',
  71. backgroundColor: getCellBgColor(dateCell)
  72. }"
  73. @click.stop="selectDateCell(dateCell)"
  74. >
  75. <!-- 顶部文本 -->
  76. <cl-text
  77. :size="20"
  78. :color="getCellTextColor(dateCell)"
  79. :pt="{
  80. className: 'absolute top-[2px]'
  81. }"
  82. >{{ dateCell.topText }}</cl-text
  83. >
  84. <!-- 主日期数字 -->
  85. <cl-text
  86. :color="getCellTextColor(dateCell)"
  87. :size="`${fontSize}px`"
  88. :pt="{
  89. className: 'font-bold'
  90. }"
  91. >{{ dateCell.date }}</cl-text
  92. >
  93. <!-- 底部文本 -->
  94. <cl-text
  95. :size="20"
  96. :color="getCellTextColor(dateCell)"
  97. :pt="{
  98. className: 'absolute bottom-[2px]'
  99. }"
  100. >{{ dateCell.bottomText }}</cl-text
  101. >
  102. </view>
  103. </view>
  104. <!-- #endif -->
  105. </view>
  106. </view>
  107. </template>
  108. <script lang="ts" setup>
  109. import { computed, nextTick, onMounted, ref, watch, type PropType } from "vue";
  110. import { ctx, dayUts, first, isDark, isHarmony, parsePt, useRefs } from "@/cool";
  111. import CalendarPicker from "./picker.uvue";
  112. import { $t, t } from "@/locale";
  113. import type { ClCalendarDateConfig, ClCalendarMode } from "../../types";
  114. import { useSize } from "../../hooks";
  115. defineOptions({
  116. name: "cl-calendar"
  117. });
  118. // 日期单元格数据结构
  119. type DateCell = {
  120. date: string; // 显示的日期数字
  121. isCurrentMonth: boolean; // 是否属于当前显示月份
  122. isToday: boolean; // 是否为今天
  123. isSelected: boolean; // 是否被选中
  124. isRange: boolean; // 是否在选择范围内
  125. fullDate: string; // 完整日期格式 YYYY-MM-DD
  126. isDisabled: boolean; // 是否被禁用
  127. isHide: boolean; // 是否隐藏显示
  128. topText: string; // 顶部文案
  129. bottomText: string; // 底部文案
  130. color: string; // 颜色
  131. };
  132. // 组件属性定义
  133. const props = defineProps({
  134. // 透传样式配置
  135. pt: {
  136. type: Object,
  137. default: () => ({})
  138. },
  139. // 当前选中的日期值(单选模式)
  140. modelValue: {
  141. type: String as PropType<string | null>,
  142. default: null
  143. },
  144. // 选中的日期数组(多选/范围模式)
  145. date: {
  146. type: Array as PropType<string[]>,
  147. default: () => []
  148. },
  149. // 日期选择模式:单选/多选/范围选择
  150. mode: {
  151. type: String as PropType<ClCalendarMode>,
  152. default: "single"
  153. },
  154. // 日期配置
  155. dateConfig: {
  156. type: Array as PropType<ClCalendarDateConfig[]>,
  157. default: () => []
  158. },
  159. // 开始日期,可选日期的开始
  160. start: {
  161. type: String
  162. },
  163. // 结束日期,可选日期的结束
  164. end: {
  165. type: String
  166. },
  167. // 设置年份
  168. year: {
  169. type: Number
  170. },
  171. // 设置月份
  172. month: {
  173. type: Number
  174. },
  175. // 是否显示其他月份的日期
  176. showOtherMonth: {
  177. type: Boolean,
  178. default: true
  179. },
  180. // 是否显示头部导航栏
  181. showHeader: {
  182. type: Boolean,
  183. default: true
  184. },
  185. // 是否显示星期
  186. showWeeks: {
  187. type: Boolean,
  188. default: true
  189. }
  190. });
  191. // 事件发射器定义
  192. const emit = defineEmits(["update:modelValue", "update:date", "change"]);
  193. // 透传样式属性类型
  194. type PassThrough = {
  195. className?: string;
  196. };
  197. // 解析透传样式配置
  198. const pt = computed(() => parsePt<PassThrough>(props.pt));
  199. // 字体大小
  200. const { getPxValue } = useSize();
  201. // 主色
  202. const color = ref(ctx.color["primary-500"] as string);
  203. // 单元格高度
  204. const cellHeight = ref(66);
  205. // 单元格间距
  206. const cellGap = ref(0);
  207. // 字体大小
  208. const fontSize = computed(() => {
  209. // #ifdef APP
  210. return getPxValue("14px");
  211. // #endif
  212. // #ifndef APP
  213. return 14;
  214. // #endif
  215. });
  216. // 当前月份日期颜色
  217. const textColor = computed(() => {
  218. return isDark.value ? "white" : (ctx.color["surface-700"] as string);
  219. });
  220. // 其他月份日期颜色
  221. const textOtherMonthColor = computed(() => {
  222. return isDark.value
  223. ? (ctx.color["surface-500"] as string)
  224. : (ctx.color["surface-300"] as string);
  225. });
  226. // 禁用日期颜色
  227. const textDisabledColor = computed(() => {
  228. return isDark.value
  229. ? (ctx.color["surface-500"] as string)
  230. : (ctx.color["surface-300"] as string);
  231. });
  232. // 今天日期颜色
  233. const textTodayColor = ref("#ff6b6b");
  234. // 选中日期颜色
  235. const textSelectedColor = ref("#ffffff");
  236. // 选中日期背景颜色
  237. const bgSelectedColor = ref(color.value);
  238. // 范围选择背景颜色
  239. const bgRangeColor = ref(isHarmony() ? (ctx.color["primary-50"] as string) : color.value + "11");
  240. // 组件引用管理器
  241. const refs = useRefs();
  242. // 日历视图DOM元素引用
  243. const viewRef = ref<UniElement | null>(null);
  244. // 当前显示的年份
  245. const currentYear = ref(0);
  246. // 当前显示的月份
  247. const currentMonth = ref(0);
  248. // 视图高度
  249. const viewHeight = computed(() => {
  250. return cellHeight.value * 6;
  251. });
  252. // 单元格宽度
  253. const cellWidth = ref(0);
  254. // 星期标签数组
  255. const weekLabels = computed(() => {
  256. return [t("周日"), t("周一"), t("周二"), t("周三"), t("周四"), t("周五"), t("周六")];
  257. });
  258. // 日历日期矩阵数据(6行7列)
  259. const dateMatrix = ref<DateCell[][]>([]);
  260. // 当前选中的日期列表
  261. const selectedDates = ref<string[]>([]);
  262. /**
  263. * 获取日历视图元素的位置信息
  264. */
  265. async function getViewRect(): Promise<DOMRect | null> {
  266. return viewRef.value!.getBoundingClientRectAsync();
  267. }
  268. /**
  269. * 判断指定日期是否被选中
  270. * @param dateStr 日期字符串 YYYY-MM-DD
  271. */
  272. function isDateSelected(dateStr: string): boolean {
  273. if (props.mode == "single") {
  274. // 单选模式:检查是否为唯一选中日期
  275. return selectedDates.value[0] == dateStr;
  276. } else {
  277. // 多选/范围模式:检查是否在选中列表中
  278. return selectedDates.value.includes(dateStr);
  279. }
  280. }
  281. /**
  282. * 判断指定日期是否被禁用
  283. * @param dateStr 日期字符串 YYYY-MM-DD
  284. */
  285. function isDateDisabled(dateStr: string): boolean {
  286. // 大于开始日期
  287. if (props.start != null) {
  288. if (dayUts(dateStr).isBefore(dayUts(props.start))) {
  289. return true;
  290. }
  291. }
  292. // 小于结束日期
  293. if (props.end != null) {
  294. if (dayUts(dateStr).isAfter(dayUts(props.end))) {
  295. return true;
  296. }
  297. }
  298. return props.dateConfig.some((config) => config.date == dateStr && config.disabled == true);
  299. }
  300. /**
  301. * 判断指定日期是否在选择范围内(不包括端点)
  302. * @param dateStr 日期字符串 YYYY-MM-DD
  303. */
  304. function isDateInRange(dateStr: string): boolean {
  305. // 仅范围选择模式且已选择两个端点时才有范围
  306. if (props.mode != "range" || selectedDates.value.length != 2) {
  307. return false;
  308. }
  309. const [startDate, endDate] = selectedDates.value;
  310. const currentDate = dayUts(dateStr);
  311. return currentDate.isAfter(startDate) && currentDate.isBefore(endDate);
  312. }
  313. /**
  314. * 获取单元格字体颜色
  315. * @param dateCell 日期单元格数据
  316. * @returns 字体颜色
  317. */
  318. function getCellTextColor(dateCell: DateCell): string {
  319. // 选中的日期文字颜色
  320. if (dateCell.isSelected) {
  321. return textSelectedColor.value;
  322. }
  323. if (dateCell.color != "") {
  324. return dateCell.color;
  325. }
  326. // 范围选择日期颜色
  327. if (dateCell.isRange) {
  328. return color.value;
  329. }
  330. // 禁用的日期颜色
  331. if (dateCell.isDisabled) {
  332. return textDisabledColor.value;
  333. }
  334. // 今天日期颜色
  335. if (dateCell.isToday) {
  336. return textTodayColor.value;
  337. }
  338. // 当前月份日期颜色
  339. if (dateCell.isCurrentMonth) {
  340. return textColor.value;
  341. }
  342. // 其他月份日期颜色
  343. return textOtherMonthColor.value;
  344. }
  345. /**
  346. * 获取单元格背景颜色
  347. * @param dateCell 日期单元格数据
  348. * @returns 背景颜色
  349. */
  350. function getCellBgColor(dateCell: DateCell): string {
  351. if (dateCell.isSelected) {
  352. return bgSelectedColor.value;
  353. }
  354. if (dateCell.isRange) {
  355. return bgRangeColor.value;
  356. }
  357. return "transparent";
  358. }
  359. /**
  360. * 计算并生成日历矩阵数据
  361. * 生成6行7列共42个日期,包含上月末尾和下月开头的日期
  362. */
  363. function calculateDateMatrix() {
  364. const weekRows: DateCell[][] = [];
  365. const todayStr = dayUts().format("YYYY-MM-DD"); // 今天的日期字符串
  366. // 获取当前月第一天
  367. const monthFirstDay = dayUts(`${currentYear.value}-${currentMonth.value}-01`);
  368. const firstDayWeekIndex = monthFirstDay.getDay(); // 第一天是星期几 (0=周日, 6=周六)
  369. // 计算日历显示的起始日期(可能是上个月的日期)
  370. const calendarStartDate = monthFirstDay.subtract(firstDayWeekIndex, "day");
  371. // 生成6周的日期数据(6行 × 7列 = 42天)
  372. let iterateDate = calendarStartDate;
  373. for (let weekIndex = 0; weekIndex < 6; weekIndex++) {
  374. const weekDates: DateCell[] = [];
  375. for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
  376. const fullDateStr = iterateDate.format("YYYY-MM-DD");
  377. const nativeDate = iterateDate.toDate();
  378. const dayNumber = nativeDate.getDate();
  379. // 判断是否属于当前显示月份
  380. const belongsToCurrentMonth =
  381. nativeDate.getMonth() + 1 == currentMonth.value &&
  382. nativeDate.getFullYear() == currentYear.value;
  383. // 日期配置
  384. const dateConfig = props.dateConfig.find((config) => config.date == fullDateStr);
  385. // 构建日期单元格数据
  386. const dateCell = {
  387. date: `${dayNumber}`,
  388. isCurrentMonth: belongsToCurrentMonth,
  389. isToday: fullDateStr == todayStr,
  390. isSelected: isDateSelected(fullDateStr),
  391. isRange: isDateInRange(fullDateStr),
  392. fullDate: fullDateStr,
  393. isDisabled: isDateDisabled(fullDateStr),
  394. isHide: false,
  395. topText: dateConfig?.topText ?? "",
  396. bottomText: dateConfig?.bottomText ?? "",
  397. color: dateConfig?.color ?? ""
  398. } as DateCell;
  399. // 根据配置决定是否隐藏相邻月份的日期
  400. if (!props.showOtherMonth && !belongsToCurrentMonth) {
  401. dateCell.isHide = true;
  402. }
  403. weekDates.push(dateCell);
  404. iterateDate = iterateDate.add(1, "day"); // 移动到下一天
  405. }
  406. weekRows.push(weekDates);
  407. }
  408. dateMatrix.value = weekRows;
  409. }
  410. /**
  411. * 使用Canvas绘制日历(仅APP端)
  412. * Web端使用DOM渲染,APP端使用Canvas提升性能
  413. */
  414. async function renderCalendar() {
  415. // #ifdef APP
  416. await nextTick(); // 等待DOM更新完成
  417. const ctx = viewRef.value!.getDrawableContext();
  418. if (ctx == null) return;
  419. ctx!.reset(); // 清空画布
  420. /**
  421. * 绘制单个日期单元格
  422. * @param dateCell 日期单元格数据
  423. * @param colIndex 列索引 (0-6)
  424. * @param rowIndex 行索引 (0-5)
  425. */
  426. function drawSingleCell(dateCell: DateCell, colIndex: number, rowIndex: number) {
  427. // 计算单元格位置
  428. const cellX = colIndex * cellWidth.value;
  429. const cellY = rowIndex * cellHeight.value;
  430. const centerX = cellX + cellWidth.value / 2;
  431. const centerY = cellY + cellHeight.value / 2;
  432. // 绘制背景(选中状态或范围状态)
  433. if (dateCell.isSelected || dateCell.isRange) {
  434. const padding = cellGap.value; // 使用间距作为内边距
  435. const bgX = cellX + padding;
  436. const bgY = cellY + padding;
  437. const bgWidth = cellWidth.value - padding * 2;
  438. const bgHeight = cellHeight.value - padding * 2;
  439. // 设置背景颜色
  440. if (dateCell.isSelected) {
  441. ctx!.fillStyle = bgSelectedColor.value;
  442. }
  443. if (dateCell.isRange) {
  444. ctx!.fillStyle = bgRangeColor.value;
  445. }
  446. ctx!.fillRect(bgX, bgY, bgWidth, bgHeight); // 绘制背景矩形
  447. }
  448. // 获取单元格文字颜色
  449. const cellTextColor = getCellTextColor(dateCell);
  450. ctx!.textAlign = "center";
  451. // 绘制顶部文本
  452. if (dateCell.topText != "") {
  453. ctx!.font = `${Math.floor(fontSize.value * 0.75)}px sans-serif`;
  454. ctx!.fillStyle = cellTextColor;
  455. const topY = cellY + 16; // 距离顶部
  456. ctx!.fillText(dateCell.topText, centerX, topY);
  457. }
  458. // 绘制主日期数字
  459. ctx!.font = `${fontSize.value}px sans-serif`;
  460. ctx!.fillStyle = cellTextColor;
  461. const textOffsetY = (fontSize.value / 2) * 0.7;
  462. ctx!.fillText(dateCell.date.toString(), centerX, centerY + textOffsetY);
  463. // 绘制底部文本
  464. if (dateCell.bottomText != "") {
  465. ctx!.font = `${Math.floor(fontSize.value * 0.75)}px sans-serif`;
  466. ctx!.fillStyle = cellTextColor;
  467. const bottomY = cellY + cellHeight.value - 8; // 距离底部
  468. ctx!.fillText(dateCell.bottomText, centerX, bottomY);
  469. }
  470. }
  471. // 获取容器尺寸信息
  472. const viewRect = await getViewRect();
  473. if (viewRect == null) {
  474. return;
  475. }
  476. // 计算单元格宽度(总宽度除以7列)
  477. const cellSize = viewRect.width / 7;
  478. // 更新渲染配置
  479. cellWidth.value = cellSize;
  480. // 遍历日期矩阵进行绘制
  481. for (let rowIndex = 0; rowIndex < dateMatrix.value.length; rowIndex++) {
  482. const weekRow = dateMatrix.value[rowIndex];
  483. for (let colIndex = 0; colIndex < weekRow.length; colIndex++) {
  484. const dateCell = weekRow[colIndex];
  485. if (!dateCell.isHide) {
  486. drawSingleCell(dateCell, colIndex, rowIndex);
  487. }
  488. }
  489. }
  490. ctx!.update(); // 更新画布显示
  491. // #endif
  492. }
  493. /**
  494. * 处理日期单元格选择逻辑
  495. * @param dateCell 被点击的日期单元格
  496. */
  497. function selectDateCell(dateCell: DateCell) {
  498. // 隐藏或禁用的日期不可选择
  499. if (dateCell.isHide || dateCell.isDisabled) {
  500. return;
  501. }
  502. if (props.mode == "single") {
  503. // 单选模式:直接替换选中日期
  504. selectedDates.value = [dateCell.fullDate];
  505. emit("update:modelValue", dateCell.fullDate);
  506. } else if (props.mode == "multiple") {
  507. // 多选模式:切换选中状态
  508. const existingIndex = selectedDates.value.indexOf(dateCell.fullDate);
  509. if (existingIndex >= 0) {
  510. // 已选中则移除
  511. selectedDates.value.splice(existingIndex, 1);
  512. } else {
  513. // 未选中则添加
  514. selectedDates.value.push(dateCell.fullDate);
  515. }
  516. } else {
  517. // 范围选择模式
  518. if (selectedDates.value.length == 0) {
  519. // 第一次点击:设置起始日期
  520. selectedDates.value = [dateCell.fullDate];
  521. } else if (selectedDates.value.length == 1) {
  522. // 第二次点击:设置结束日期
  523. const startDate = dayUts(selectedDates.value[0]);
  524. const endDate = dayUts(dateCell.fullDate);
  525. if (endDate.isBefore(startDate)) {
  526. // 结束日期早于开始日期时自动交换
  527. selectedDates.value = [dateCell.fullDate, selectedDates.value[0]];
  528. } else {
  529. selectedDates.value = [selectedDates.value[0], dateCell.fullDate];
  530. }
  531. } else {
  532. // 已有范围时重新开始选择
  533. selectedDates.value = [dateCell.fullDate];
  534. }
  535. }
  536. // 发射更新事件
  537. emit("update:date", [...selectedDates.value]);
  538. emit("change", selectedDates.value);
  539. // 重新计算日历数据并重绘
  540. calculateDateMatrix();
  541. renderCalendar();
  542. }
  543. /**
  544. * 处理年月选择器的变化事件
  545. * @param yearMonthArray [年份, 月份] 数组
  546. */
  547. function onYearMonthChange(yearMonthArray: number[]) {
  548. currentYear.value = yearMonthArray[0];
  549. currentMonth.value = yearMonthArray[1];
  550. // 重新计算日历数据并重绘
  551. calculateDateMatrix();
  552. renderCalendar();
  553. }
  554. /**
  555. * 处理点击事件(APP端点击检测)
  556. */
  557. async function onTap(e: UniPointerEvent) {
  558. // 获取容器位置信息
  559. const viewRect = await getViewRect();
  560. if (viewRect == null) {
  561. return;
  562. }
  563. // 计算触摸点相对于容器的坐标
  564. const relativeX = e.clientX - viewRect.left;
  565. const relativeY = e.clientY - viewRect.top;
  566. // 根据坐标计算对应的行列索引
  567. const columnIndex = Math.floor(relativeX / cellWidth.value);
  568. const rowIndex = Math.floor(relativeY / cellHeight.value);
  569. // 边界检查:确保索引在有效范围内
  570. if (
  571. rowIndex < 0 ||
  572. rowIndex >= dateMatrix.value.length ||
  573. columnIndex < 0 ||
  574. columnIndex >= 7
  575. ) {
  576. return;
  577. }
  578. const targetDateCell = dateMatrix.value[rowIndex][columnIndex];
  579. selectDateCell(targetDateCell);
  580. }
  581. /**
  582. * 切换到上一个月
  583. */
  584. function gotoPrevMonth() {
  585. const [newYear, newMonth] = dayUts(`${currentYear.value}-${currentMonth.value}-01`)
  586. .subtract(1, "month")
  587. .toArray();
  588. currentYear.value = newYear;
  589. currentMonth.value = newMonth;
  590. // 重新计算并渲染日历
  591. calculateDateMatrix();
  592. renderCalendar();
  593. }
  594. /**
  595. * 切换到下一个月
  596. */
  597. function gotoNextMonth() {
  598. const [newYear, newMonth] = dayUts(`${currentYear.value}-${currentMonth.value}-01`)
  599. .add(1, "month")
  600. .toArray();
  601. currentYear.value = newYear;
  602. currentMonth.value = newMonth;
  603. // 重新计算并渲染日历
  604. calculateDateMatrix();
  605. renderCalendar();
  606. }
  607. /**
  608. * 解析选中日期
  609. */
  610. function parseDate(flag: boolean | null = null) {
  611. // 根据选择模式初始化选中日期
  612. if (props.mode == "single") {
  613. selectedDates.value = props.modelValue != null ? [props.modelValue] : [];
  614. } else {
  615. selectedDates.value = [...props.date];
  616. }
  617. // 获取初始显示日期(优先使用选中日期,否则使用当前日期)
  618. let [year, month] = dayUts(first(selectedDates.value)).toArray();
  619. if (flag == true) {
  620. year = props.year ?? year;
  621. month = props.month ?? month;
  622. }
  623. currentYear.value = year;
  624. currentMonth.value = month;
  625. // 计算初始日历数据
  626. calculateDateMatrix();
  627. // 渲染日历视图
  628. renderCalendar();
  629. }
  630. // 组件挂载时的初始化逻辑
  631. onMounted(() => {
  632. // 解析日期
  633. parseDate(true);
  634. // 监听单选模式的值变化
  635. watch(
  636. computed(() => props.modelValue ?? ""),
  637. (newValue: string) => {
  638. selectedDates.value = [newValue];
  639. parseDate();
  640. }
  641. );
  642. // 监听多选/范围模式的值变化
  643. watch(
  644. computed(() => props.date),
  645. (newDateArray: string[]) => {
  646. selectedDates.value = [...newDateArray];
  647. parseDate();
  648. }
  649. );
  650. // 重新渲染
  651. watch(
  652. computed(() => [props.dateConfig, props.showOtherMonth]),
  653. () => {
  654. calculateDateMatrix();
  655. renderCalendar();
  656. },
  657. {
  658. deep: true
  659. }
  660. );
  661. });
  662. </script>
  663. <style lang="scss" scoped>
  664. /* 日历组件主容器 */
  665. .cl-calendar {
  666. @apply relative;
  667. /* 头部导航栏样式 */
  668. &__header {
  669. @apply flex flex-row items-center justify-between p-3 w-full;
  670. /* 上一月/下一月按钮样式 */
  671. &-prev,
  672. &-next {
  673. @apply flex flex-row items-center justify-center rounded-full bg-surface-100;
  674. width: 60rpx;
  675. height: 60rpx;
  676. /* 暗色模式适配 */
  677. &.is-dark {
  678. @apply bg-surface-700;
  679. }
  680. }
  681. /* 当前年月显示区域 */
  682. &-date {
  683. @apply flex flex-row items-center justify-center;
  684. }
  685. }
  686. /* 星期标题行样式 */
  687. &__weeks {
  688. @apply flex flex-row;
  689. /* 单个星期标题样式 */
  690. &-item {
  691. @apply flex flex-row items-center justify-center flex-1;
  692. height: 80rpx;
  693. }
  694. }
  695. /* 日期网格容器样式 */
  696. &__view {
  697. @apply w-full;
  698. // #ifndef APP
  699. /* 日期行样式 */
  700. &-row {
  701. @apply flex flex-row;
  702. }
  703. /* 日期单元格样式 */
  704. &-cell {
  705. @apply flex-1 flex flex-col items-center justify-center relative;
  706. height: 80rpx;
  707. /* 隐藏状态(相邻月份日期) */
  708. &.is-hide {
  709. opacity: 0;
  710. }
  711. /* 禁用状态 */
  712. &.is-disabled {
  713. @apply opacity-50;
  714. }
  715. }
  716. // #endif
  717. }
  718. }
  719. </style>