// components/w-datetime-picker/index.ts /** * 格式化时长 * @param num 时长 可以传负 */ function formatTime(num: number) { const date = new Date(); date.setFullYear(date.getFullYear() + num); return date.getTime(); } /** * 时长填充 * @param value 值 * @param maxLength 长度 * @param fillText 填充内容 * @returns 填充值 */ function padStartString(value: any, maxLength = 2, fillText = "0") { const text = value + ""; return text.padStart(maxLength, fillText); } Component({ options: { multipleSlots: true, styleIsolation: "shared", }, /** * 组件的属性列表 */ properties: { value: { type: Number as any, value: null, observer: "_value", }, /** 是否显示 */ show: { type: Boolean, value: false, observer: "_show", }, /** 类型,可选值为 date time year-month 不建议动态修改 */ type: { type: String, value: "datetime", }, zIndex: { type: Number, value: 100, }, minDate: { type: Number, value: formatTime(-20), }, maxDate: { type: Number, value: formatTime(20), }, /** * 可见的选项个数 */ visibleItemCount: { type: Number, value: 6, }, itemHeight: { type: Number, value: 46, }, }, /** * 组件的初始数据 */ data: { innerShow: false, // showAfterLeave: false, innerValue: null as any, // 单列时为string, 多列为array // defaultIndex: 0, // 默认选中的index 单行显示的 // innerLoading: false, formatter(type: string, value: any) { if (type === "year") { return `${value}年`; } if (type === "month") { return `${value}月`; } if (type === "day") { return `${value}日`; } if (type === "hour") { return `${value}时`; } if (type === "minute") { return `${value}分`; } return value; }, }, lifetimes: { attached() { if (this.data.type !== "time" && !this.data.value) { this.setData({ innerValue: Date.now(), }); } }, }, /** * 组件的方法列表 */ methods: { onSubmit(event: any) { const date = new Date(event.detail); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const detail = { chName: "", value: event.detail, }; const type = this.data.type; if (type === "datetime") { detail.chName = year + "年" + padStartString(month) + "月" + padStartString(day) + "日 " + padStartString(hour) + "时" + padStartString(minute) + "分"; } else if (type === "date") { detail.chName = year + "年" + padStartString(month) + "月" + padStartString(day) + "日"; } else if (type === "year-month") { detail.chName = year + "年" + padStartString(month) + "月"; } else if (type === "time") { detail.chName = padStartString(hour) + "分" + padStartString(minute) + "秒"; } this.setData({ value: detail.value, }); this.triggerEvent("confirm", detail); this.triggerEvent("input", detail.value); }, onClose() { this.triggerEvent("cancel"); }, // onAfterLeave() { // this.setData({ // showAfterLeave: true, // }); // }, // onBeforeEnter() { // this.setData({ // showAfterLeave: false, // }); // }, _show() { // 单行显示 需要设置默认选中的index this.setData({ innerShow: this.data.show, }); }, _value() { if (!this.data.value) return; this.setData({ innerValue: this.data.value, }); }, }, });