cl-calendar.uvue 20 KB

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