Component({ options: { addGlobalClass: true }, properties: { iconName: { type: String, value: "icon-rili1" }, title: { type: String, }, onChange: { type: Function, }, fields: { type: String, value: "day", //有效值 year,month,day,表示选择器的粒度 }, end: { type: [String, Number] }, start: { type: [String, Number] }, type: { type: String, value: "" }, startMonth: { type: [String, Number], value: 1 }, endMonth: { type: [String, Number], value: 12 } }, lifetimes: { attached: function () { const fields = this.properties.fields; let value = new Date(); if (fields === "year") { value = value.getFullYear().toString(); } else if (fields === "month") { const year = value.getFullYear(); const month = (value.getMonth() + 1).toString().padStart(2, '0'); value = `${year}-${month}`; } else if (fields === "day") { value = value.toISOString().split('T')[0]; } this.setData({ value }); if (this.data.type == 'sameYear') { this.setData({ startMonth1: this.data.startMonth, endMonth1: this.data.endMonth, year: value }) } } }, data: { value: new Date().toISOString().split('T')[0], // 默认值为今天,格式为 YYYY-MM-DD showSameYear: false, }, methods: { onChange(e) { if (e.detail.value == this.data.value) return; this.setData({ value: e.detail.value }) this.triggerEvent("onChange", e.detail.value) }, openSameYear() { this.setData({ showSameYear: true }) }, onClose() { this.setData({ showSameYear: false }) }, onMonthTap(e) { const { month } = e.currentTarget.dataset; const { startMonth1, endMonth1 } = this.data; // 情况1:当前没有任何选中 if (startMonth1 === null && endMonth1 === null) { this.setData({ startMonth1: month, endMonth1: month }); } // 情况2:当前只选中了一个月份(单点选择状态) else if (startMonth1 === endMonth1) { // 如果点击同一个月份,取消选中 if (month === startMonth1) { this.setData({ startMonth1: null, endMonth1: null }); } // 如果点击不同月份,形成区间 else { const newStart = Math.min(startMonth1, month); const newEnd = Math.max(startMonth1, month); this.setData({ startMonth1: newStart, endMonth1: newEnd }); } } // 情况3:当前已经是一个区间 else { // 点击任意月份,重置为单点选择 this.setData({ startMonth1: month, endMonth1: month }); } }, onYear(e) { this.setData({ year: e.detail.value }) }, onConfirm() { const { startMonth1, endMonth1, year } = this.data; if (!year) { wx.showModal({ title: '提示', content: '请选择年份', showCancel: false }) return; } else if (!startMonth1 && !endMonth1) { wx.showModal({ title: '提示', content: '请选择月份范围', showCancel: false }) return; } this.setData({ value: year }) this.triggerEvent("onChange", { startMonth: startMonth1 || endMonth1, endMonth: endMonth1 || startMonth1, year }) } } })