cl-calendar.uvue 19 KB

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