cl-select-date.uvue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <template>
  2. <cl-select-trigger
  3. v-if="showTrigger"
  4. :pt="{
  5. className: pt.trigger?.className,
  6. icon: pt.trigger?.icon
  7. }"
  8. :placeholder="placeholder"
  9. :disabled="disabled"
  10. :focus="popupRef?.isOpen"
  11. :text="text"
  12. arrow-icon="calendar-line"
  13. @tap="open()"
  14. @clear="clear"
  15. ></cl-select-trigger>
  16. <cl-popup
  17. ref="popupRef"
  18. v-model="visible"
  19. :title="title"
  20. :pt="{
  21. className: pt.popup?.className,
  22. header: pt.popup?.header,
  23. container: pt.popup?.container,
  24. mask: pt.popup?.mask,
  25. draw: pt.popup?.draw
  26. }"
  27. >
  28. <view class="cl-select-popup" @touchmove.stop>
  29. <view class="cl-select-popup__picker">
  30. <cl-picker-view
  31. :headers="headers"
  32. :value="indexes"
  33. :columns="columns"
  34. @change="onChange"
  35. ></cl-picker-view>
  36. </view>
  37. <view class="cl-select-popup__op">
  38. <cl-button
  39. v-if="showCancel"
  40. size="large"
  41. text
  42. border
  43. type="light"
  44. :pt="{
  45. className: 'flex-1 !rounded-xl h-[80rpx]'
  46. }"
  47. @tap="close"
  48. >{{ cancelText }}</cl-button
  49. >
  50. <cl-button
  51. v-if="showConfirm"
  52. size="large"
  53. :pt="{
  54. className: 'flex-1 !rounded-xl h-[80rpx]'
  55. }"
  56. @tap="confirm"
  57. >{{ confirmText }}</cl-button
  58. >
  59. </view>
  60. </view>
  61. </cl-popup>
  62. </template>
  63. <script setup lang="ts">
  64. import { ref, computed, type PropType, watch, nextTick } from "vue";
  65. import type { ClSelectOption } from "../../types";
  66. import { dayUts, isEmpty, isNull, parsePt } from "@/cool";
  67. import type { ClSelectTriggerPassThrough } from "../cl-select-trigger/props";
  68. import type { ClPopupPassThrough } from "../cl-popup/props";
  69. import { t } from "@/locale";
  70. defineOptions({
  71. name: "cl-select-date"
  72. });
  73. // 组件属性定义
  74. const props = defineProps({
  75. // 透传样式配置,支持外部自定义样式
  76. pt: {
  77. type: Object,
  78. default: () => ({})
  79. },
  80. // 选择器的值,外部v-model绑定
  81. modelValue: {
  82. type: String,
  83. default: ""
  84. },
  85. // 表头
  86. headers: {
  87. type: Array as PropType<string[]>,
  88. default: () => [t("年"), t("月"), t("日"), t("时"), t("分"), t("秒")]
  89. },
  90. // 选择器标题
  91. title: {
  92. type: String,
  93. default: t("请选择")
  94. },
  95. // 选择器占位符
  96. placeholder: {
  97. type: String,
  98. default: t("请选择")
  99. },
  100. // 是否显示选择器触发器
  101. showTrigger: {
  102. type: Boolean,
  103. default: true
  104. },
  105. // 是否禁用选择器
  106. disabled: {
  107. type: Boolean,
  108. default: false
  109. },
  110. // 确认按钮文本
  111. confirmText: {
  112. type: String,
  113. default: t("确定")
  114. },
  115. // 是否显示确认按钮
  116. showConfirm: {
  117. type: Boolean,
  118. default: true
  119. },
  120. // 取消按钮文本
  121. cancelText: {
  122. type: String,
  123. default: t("取消")
  124. },
  125. // 是否显示取消按钮
  126. showCancel: {
  127. type: Boolean,
  128. default: true
  129. },
  130. // 标签格式化
  131. labelFormat: {
  132. type: String as PropType<string>,
  133. default: ""
  134. },
  135. // 值格式化
  136. valueFormat: {
  137. type: String as PropType<string>,
  138. default: ""
  139. },
  140. // 开始日期
  141. start: {
  142. type: String,
  143. default: "1950-01-01 00:00:00"
  144. },
  145. // 结束日期
  146. end: {
  147. type: String,
  148. default: "2050-12-31 23:59:59"
  149. },
  150. // 类型,控制选择的粒度
  151. type: {
  152. type: String as PropType<"year" | "month" | "date" | "hour" | "minute" | "second">,
  153. default: "second"
  154. }
  155. });
  156. // 定义事件,支持v-model和change事件
  157. const emit = defineEmits(["update:modelValue", "change"]);
  158. // 弹出层引用,用于控制popup的显示与隐藏
  159. const popupRef = ref<ClPopupComponentPublicInstance | null>(null);
  160. // 透传样式类型定义,支持trigger和popup的样式透传
  161. type PassThrough = {
  162. trigger?: ClSelectTriggerPassThrough;
  163. popup?: ClPopupPassThrough;
  164. };
  165. // 解析透传样式配置,返回合并后的样式对象
  166. const pt = computed(() => parsePt<PassThrough>(props.pt));
  167. // 格式化类型
  168. const formatType = computed(() => {
  169. switch (props.type) {
  170. case "year":
  171. return "YYYY";
  172. case "month":
  173. return "YYYY-MM";
  174. case "date":
  175. return "YYYY-MM-DD";
  176. case "hour":
  177. case "minute":
  178. case "second":
  179. return "YYYY-MM-DD HH:mm:ss";
  180. default:
  181. return "YYYY-MM-DD HH:mm:ss";
  182. }
  183. });
  184. // 标签格式化
  185. const labelFormat = computed(() => {
  186. if (isNull(props.labelFormat) || isEmpty(props.labelFormat)) {
  187. return formatType.value;
  188. }
  189. return props.labelFormat;
  190. });
  191. // 值格式化
  192. const valueFormat = computed(() => {
  193. if (isNull(props.valueFormat) || isEmpty(props.valueFormat)) {
  194. return formatType.value;
  195. }
  196. return props.valueFormat;
  197. });
  198. // 当前选中的值,存储为数组,依次为年月日时分秒
  199. const value = ref<number[]>([]);
  200. // 时间选择器列表,动态生成每一列的选项
  201. const list = computed(() => {
  202. // 解析开始日期为年月日时分秒数组
  203. const [startYear, startMonth, startDate, startHour, startMinute, startSecond] = dayUts(
  204. props.start
  205. ).toArray();
  206. // 解析结束日期为年月日时分秒数组
  207. const [endYear, endMonth, endDate, endHour, endMinute, endSecond] = dayUts(props.end).toArray();
  208. // 获取当前选中的年月日时分秒值
  209. const [year, month, date, hour, minute] = value.value;
  210. // 初始化年月日时分秒六个选项数组
  211. const arr = [[], [], [], [], [], []] as ClSelectOption[][];
  212. // 判断是否为闰年
  213. const isLeapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
  214. // 根据月份和是否闰年获取当月天数
  215. const days = [31, isLeapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
  216. // 计算年份范围,确保至少有60年可选
  217. const yearRange = Math.max(60, endYear - startYear + 1);
  218. // 遍历生成年月日时分秒的选项
  219. for (let i = 0; i < yearRange; i++) {
  220. // 计算当前遍历的年份
  221. const yearNum = startYear + i;
  222. // 如果年份在结束年份范围内,添加到年份选项
  223. if (yearNum <= endYear) {
  224. arr[0].push({
  225. label: yearNum.toString(),
  226. value: yearNum
  227. });
  228. }
  229. // 处理月份选项
  230. let monthNum = startYear == year ? startMonth + i : i + 1;
  231. let endMonthNum = endYear == year ? endMonth : 12;
  232. // 添加有效的月份选项
  233. if (monthNum <= endMonthNum) {
  234. arr[1].push({
  235. label: monthNum.toString().padStart(2, "0"),
  236. value: monthNum
  237. });
  238. }
  239. // 处理日期选项
  240. let dateNum = startYear == year && startMonth == month ? startDate + i : i + 1;
  241. let endDateNum = endYear == year && endMonth == month ? endDate : days;
  242. // 添加有效的日期选项
  243. if (dateNum <= endDateNum) {
  244. arr[2].push({
  245. label: dateNum.toString().padStart(2, "0"),
  246. value: dateNum
  247. });
  248. }
  249. // 处理小时选项
  250. let hourNum =
  251. startYear == year && startMonth == month && startDate == date ? startHour + i : i;
  252. let endHourNum = endYear == year && endMonth == month && endDate == date ? endHour : 24;
  253. // 添加有效的小时选项
  254. if (hourNum < endHourNum) {
  255. arr[3].push({
  256. label: hourNum.toString().padStart(2, "0"),
  257. value: hourNum
  258. });
  259. }
  260. // 处理分钟选项
  261. let minuteNum =
  262. startYear == year && startMonth == month && startDate == date && startHour == hour
  263. ? startMinute + i
  264. : i;
  265. let endMinuteNum =
  266. endYear == year && endMonth == month && endDate == date && endHour == hour
  267. ? endMinute
  268. : 60;
  269. // 添加有效的分钟选项
  270. if (minuteNum < endMinuteNum) {
  271. arr[4].push({
  272. label: minuteNum.toString().padStart(2, "0"),
  273. value: minuteNum
  274. });
  275. }
  276. // 处理秒钟选项
  277. let secondNum =
  278. startYear == year &&
  279. startMonth == month &&
  280. startDate == date &&
  281. startHour == hour &&
  282. startMinute == minute
  283. ? startSecond + i
  284. : i;
  285. let endSecondNum =
  286. endYear == year &&
  287. endMonth == month &&
  288. endDate == date &&
  289. endHour == hour &&
  290. endMinute == minute
  291. ? endSecond
  292. : 60;
  293. // 添加有效的秒钟选项
  294. if (secondNum < endSecondNum) {
  295. arr[5].push({
  296. label: secondNum.toString().padStart(2, "0"),
  297. value: secondNum
  298. });
  299. }
  300. }
  301. // 返回包含所有时间选项的数组
  302. return arr;
  303. });
  304. // 列数,决定显示多少列(年、月、日、时、分、秒)
  305. const columnNum = computed(() => {
  306. return (
  307. ["year", "month", "date", "hour", "minute", "second"].findIndex((e) => e == props.type) + 1
  308. );
  309. });
  310. // 列数据,取出需要显示的列
  311. const columns = computed(() => {
  312. return list.value.slice(0, columnNum.value);
  313. });
  314. // 当前选中项的索引,返回每一列当前选中的下标
  315. const indexes = computed(() => {
  316. // 如果当前值为空,返回空数组
  317. if (isEmpty(value.value)) {
  318. return [];
  319. }
  320. // 遍历每一列,查找当前值在选项中的下标
  321. return value.value.map((e, i) => {
  322. const index = list.value[i].findIndex((a) => a.value == e);
  323. // 如果未找到,返回0
  324. if (index == -1) {
  325. return 0;
  326. }
  327. return index;
  328. });
  329. });
  330. // 将当前选中的年月日时分秒拼接为字符串
  331. function toDate() {
  332. // 使用数组存储日期时间各部分,避免重复字符串拼接
  333. const parts: string[] = [];
  334. // 月日时分秒需要补0对齐
  335. const units = ["", "-", "-", " ", ":", ":"];
  336. // 默认值
  337. const defaultValue = [2000, 1, 1, 0, 0, 0];
  338. // 遍历处理各个时间单位
  339. units.forEach((key, i) => {
  340. let val = value.value[i];
  341. // 超出当前列数时,使用默认值
  342. if (i >= columnNum.value) {
  343. val = defaultValue[i];
  344. }
  345. // 拼接字符串并补0
  346. parts.push(key + val.toString().padStart(2, "0"));
  347. });
  348. // 拼接所有部分返回
  349. return parts.join("");
  350. }
  351. // 显示文本,展示当前选中的日期字符串
  352. const text = ref("");
  353. // 获取显示文本,格式化为labelFormat格式
  354. function getText() {
  355. text.value = dayUts(toDate()).format(labelFormat.value);
  356. }
  357. // 选择器值改变事件,更新value
  358. async function onChange(arr: number[]) {
  359. for (let i = 0; i < arr.length; i++) {
  360. value.value[i] = list.value[i][arr[i]].value as number;
  361. }
  362. }
  363. // 选择器显示状态,控制popup显示
  364. const visible = ref(false);
  365. // 选择回调函数
  366. let callback: ((value: string) => void) | null = null;
  367. // 打开选择器
  368. function open(cb: ((value: string) => void) | null = null) {
  369. if (props.disabled) {
  370. return;
  371. }
  372. visible.value = true;
  373. callback = cb;
  374. }
  375. // 关闭选择器,设置visible为false
  376. function close() {
  377. visible.value = false;
  378. }
  379. // 清空选择器,重置显示文本并触发事件
  380. function clear() {
  381. text.value = "";
  382. emit("update:modelValue", "");
  383. emit("change", "");
  384. }
  385. // 确认选择,触发事件并关闭选择器
  386. function confirm() {
  387. const val = dayUts(toDate()).format(valueFormat.value);
  388. // 触发更新事件
  389. emit("update:modelValue", val);
  390. emit("change", val);
  391. // 触发回调
  392. if (callback != null) {
  393. callback!(val);
  394. }
  395. // 更新显示文本
  396. getText();
  397. // 关闭选择器
  398. close();
  399. }
  400. // 监听modelValue变化,初始化或更新value
  401. watch(
  402. computed(() => props.modelValue),
  403. (val: string) => {
  404. // 如果值为空,使用当前时间
  405. if (isNull(val) || isEmpty(val)) {
  406. value.value = dayUts().toArray();
  407. } else {
  408. // 否则解析为数组
  409. value.value = dayUts(val).toArray();
  410. getText();
  411. }
  412. },
  413. {
  414. immediate: true
  415. }
  416. );
  417. defineExpose({
  418. open,
  419. close
  420. });
  421. </script>
  422. <style lang="scss" scoped>
  423. .cl-select {
  424. &-popup {
  425. &__op {
  426. @apply flex flex-row items-center justify-center;
  427. padding: 24rpx;
  428. }
  429. }
  430. }
  431. </style>