使用 UniApp 實現一個精致的日歷組件
前言
最近在開發一個約會小程序時,需要實現一個既美觀又實用的日歷組件。市面上雖然有不少現成的組件庫,但都不太符合我們的設計需求。于是,我決定從零開始,基于 UniApp 自己實現一個功能完善、UI精致的日歷組件。本文將分享我的實現思路和過程,希望對你有所幫助。
需求分析
首先,讓我們明確一下這個日歷組件需要滿足的需求:
- 日歷展示:能夠清晰展示年、月、日信息
- 日期選擇:支持單選、范圍選擇功能
- 樣式定制:支持自定義主題顏色、特殊日期標記
- 事件標記:能夠在特定日期顯示事件標記或小紅點
- 手勢操作:支持左右滑動切換月份
- 農歷展示:可選擇性展示農歷信息
基于以上需求,我們開始設計和編碼。
實現思路
1. 數據結構設計
日歷組件的核心是對日期數據的管理。我們需要設計一個合理的數據結構來存儲和操作日期信息。
{year: 2023, // 當前顯示的年份month: 5, // 當前顯示的月份(1-12)day: 15, // 當前選中的日期weeks: [ // 按周分組的日期數據[ // 第一周{day: 30, // 日期month: 4, // 所屬月份isCurrentMonth: false, // 是否屬于當前月isToday: false, // 是否是今天isSelected: false, // 是否被選中hasEvent: false, // 是否有事件lunar: '四月初一', // 農歷信息disable: false // 是否禁用},// ... 其他日期數據],// ... 其他周數據]
}
2. 核心功能實現
首先,我們需要計算出日歷網格中的所有日期數據。這包括當前月的所有日期,以及為了填滿網格而需要顯示的上個月和下個月的部分日期。
以下是生成日歷數據的核心函數:
/*** 生成日歷數據* @param {Number} year 年份* @param {Number} month 月份(1-12)* @return {Array} 日歷數據數組*/
function generateCalendarData(year, month) {// 獲取當前月第一天是星期幾const firstDayOfMonth = new Date(year, month - 1, 1).getDay();// 獲取當前月的天數const daysInMonth = new Date(year, month, 0).getDate();// 獲取上個月的天數const daysInPrevMonth = new Date(year, month - 1, 0).getDate();// 獲取今天的日期信息const today = new Date();const isToday = (date) => {return date.getFullYear() === today.getFullYear() && date.getMonth() === today.getMonth() && date.getDate() === today.getDate();};// 日歷數據數組let days = [];// 添加上個月的日期for (let i = 0; i < firstDayOfMonth; i++) {const prevDay = daysInPrevMonth - firstDayOfMonth + i + 1;const prevMonth = month - 1 > 0 ? month - 1 : 12;const prevYear = prevMonth === 12 ? year - 1 : year;days.push({day: prevDay,month: prevMonth,year: prevYear,isCurrentMonth: false,isToday: isToday(new Date(prevYear, prevMonth - 1, prevDay)),isSelected: false,hasEvent: false, // 根據實際情況設置lunar: getLunarDate(prevYear, prevMonth, prevDay), // 獲取農歷日期disable: false});}// 添加當前月的日期for (let i = 1; i <= daysInMonth; i++) {days.push({day: i,month,year,isCurrentMonth: true,isToday: isToday(new Date(year, month - 1, i)),isSelected: false,hasEvent: false, // 根據實際情況設置lunar: getLunarDate(year, month, i), // 獲取農歷日期disable: false});}// 添加下個月的日期,補滿 6 行const totalDays = 42; // 6行7列const remainingDays = totalDays - days.length;for (let i = 1; i <= remainingDays; i++) {const nextMonth = month + 1 <= 12 ? month + 1 : 1;const nextYear = nextMonth === 1 ? year + 1 : year;days.push({day: i,month: nextMonth,year: nextYear,isCurrentMonth: false,isToday: isToday(new Date(nextYear, nextMonth - 1, i)),isSelected: false,hasEvent: false, // 根據實際情況設置lunar: getLunarDate(nextYear, nextMonth, i), // 獲取農歷日期disable: false});}// 將日期按周分組const weeks = [];for (let i = 0; i < days.length; i += 7) {weeks.push(days.slice(i, i + 7));}return weeks;
}
3. 組件開發
接下來,讓我們使用 UniApp 開發這個日歷組件。我們將創建一個獨立的組件,以便在不同項目中復用。
<!-- calendar.vue -->
<template><view class="calendar"><!-- 日歷頭部 --><view class="calendar-header"><view class="calendar-title"><text>{{ year }}年{{ month }}月</text></view><view class="calendar-controls"><view class="prev-month" @click="changeMonth(-1)"><text class="iconfont icon-left"></text></view><view class="next-month" @click="changeMonth(1)"><text class="iconfont icon-right"></text></view></view></view><!-- 星期欄 --><view class="calendar-weeks"><view class="week-item" v-for="(item, index) in weekDays" :key="index"><text :class="{'weekend': index === 0 || index === 6}">{{ item }}</text></view></view><!-- 日期網格 --><view class="calendar-days"><view class="calendar-week" v-for="(week, weekIndex) in weeks" :key="weekIndex"><viewclass="day-item"v-for="(day, dayIndex) in week":key="dayIndex":class="{'current-month': day.isCurrentMonth,'other-month': !day.isCurrentMonth,'today': day.isToday,'selected': day.isSelected,'disabled': day.disable}"@click="selectDay(day)"><view class="day-number">{{ day.day }}</view><view class="lunar-date" v-if="showLunar">{{ day.lunar }}</view><view class="event-dot" v-if="day.hasEvent"></view></view></view></view><!-- 底部操作欄 --><view class="calendar-footer" v-if="showFooter"><view class="btn-today" @click="goToToday">今天</view><view class="btn-clear" @click="clearSelection">清除</view></view></view>
</template><script>
export default {name: 'Calendar',props: {// 默認選中日期value: {type: [Date, Array],default: null},// 是否多選multiple: {type: Boolean,default: false},// 是否顯示農歷showLunar: {type: Boolean,default: true},// 是否顯示底部操作欄showFooter: {type: Boolean,default: true},// 特殊日期,包含事件的日期events: {type: Array,default: () => []},// 主題色themeColor: {type: String,default: '#2979ff'}},data() {return {year: new Date().getFullYear(),month: new Date().getMonth() + 1,weeks: [],weekDays: ['日', '一', '二', '三', '四', '五', '六'],selectedDays: []};},watch: {value: {handler(val) {this.initSelection(val);},immediate: true},events: {handler() {this.updateCalendar();}}},created() {this.updateCalendar();},methods: {// 更新日歷數據updateCalendar() {this.weeks = this.generateCalendarData(this.year, this.month);this.markEvents();this.initSelection(this.value);},// 生成日歷數據generateCalendarData(year, month) {// 實現與上文相同的函數// ...},// 切換月份changeMonth(offset) {let newMonth = this.month + offset;let newYear = this.year;if (newMonth < 1) {newMonth = 12;newYear--;} else if (newMonth > 12) {newMonth = 1;newYear++;}this.year = newYear;this.month = newMonth;this.updateCalendar();},// 選擇日期selectDay(day) {if (day.disable) return;if (this.multiple) {const index = this.selectedDays.findIndex(d => d.year === day.year && d.month === day.month && d.day === day.day);if (index === -1) {// 添加選中日期this.selectedDays.push({year: day.year,month: day.month,day: day.day});} else {// 取消選中this.selectedDays.splice(index, 1);}} else {// 單選模式this.selectedDays = [{year: day.year,month: day.month,day: day.day}];}// 更新選中狀態this.updateSelectedStatus();// 觸發事件this.$emit('input', this.getSelectedDates());this.$emit('change', this.getSelectedDates());},// 初始化選中狀態initSelection(value) {if (!value) {this.selectedDays = [];} else if (Array.isArray(value)) {this.selectedDays = value.map(date => ({year: date.getFullYear(),month: date.getMonth() + 1,day: date.getDate()}));} else if (value instanceof Date) {this.selectedDays = [{year: value.getFullYear(),month: value.getMonth() + 1,day: value.getDate()}];}this.updateSelectedStatus();},// 更新選中狀態updateSelectedStatus() {this.weeks = this.weeks.map(week => {return week.map(day => {const isSelected = this.selectedDays.some(d => d.year === day.year && d.month === day.month && d.day === day.day);return { ...day, isSelected };});});},// 標記事件markEvents() {if (!this.events || !this.events.length) return;this.weeks = this.weeks.map(week => {return week.map(day => {const hasEvent = this.events.some(event => {const eventDate = new Date(event.date);return eventDate.getFullYear() === day.year &&eventDate.getMonth() + 1 === day.month &&eventDate.getDate() === day.day;});return { ...day, hasEvent };});});},// 返回選中的日期對象getSelectedDates() {const dates = this.selectedDays.map(d => {return new Date(d.year, d.month - 1, d.day);});return this.multiple ? dates : dates[0] || null;},// 跳轉到今天goToToday() {const today = new Date();this.year = today.getFullYear();this.month = today.getMonth() + 1;this.updateCalendar();},// 清除選擇clearSelection() {this.selectedDays = [];this.updateSelectedStatus();this.$emit('input', this.multiple ? [] : null);this.$emit('change', this.multiple ? [] : null);}}
};
</script><style lang="scss">
.calendar {background-color: #fff;border-radius: 12rpx;box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);padding: 20rpx;.calendar-header {display: flex;justify-content: space-between;align-items: center;margin-bottom: 20rpx;.calendar-title {font-size: 32rpx;font-weight: bold;}.calendar-controls {display: flex;.prev-month, .next-month {width: 60rpx;height: 60rpx;display: flex;justify-content: center;align-items: center;.iconfont {font-size: 28rpx;color: #666;}}}}.calendar-weeks {display: flex;border-bottom: 1px solid #f0f0f0;padding-bottom: 10rpx;.week-item {flex: 1;text-align: center;font-size: 28rpx;color: #999;.weekend {color: #ff5252;}}}.calendar-days {.calendar-week {display: flex;margin-top: 10rpx;.day-item {flex: 1;height: 80rpx;display: flex;flex-direction: column;justify-content: center;align-items: center;position: relative;border-radius: 8rpx;&.current-month {color: #333;}&.other-month {color: #ccc;}&.today {background-color: rgba(41, 121, 255, 0.1);.day-number {font-weight: bold;}}&.selected {background-color: v-bind(themeColor);color: #fff;.lunar-date {color: rgba(255, 255, 255, 0.8);}}&.disabled {color: #ddd;cursor: not-allowed;}.day-number {font-size: 28rpx;}.lunar-date {font-size: 20rpx;color: #999;margin-top: 4rpx;}.event-dot {position: absolute;width: 8rpx;height: 8rpx;border-radius: 50%;background-color: #ff5252;bottom: 6rpx;}}}}.calendar-footer {display: flex;justify-content: flex-end;margin-top: 20rpx;.btn-today, .btn-clear {padding: 6rpx 20rpx;font-size: 24rpx;border-radius: 4rpx;margin-left: 20rpx;}.btn-today {background-color: v-bind(themeColor);color: #fff;}.btn-clear {border: 1px solid #ddd;color: #666;}}
}
</style>
農歷計算
對于農歷的計算,我們可以使用第三方庫,比如 lunar-calendar
,也可以自己實現。以下是一個簡化版的農歷計算函數:
function getLunarDate(year, month, day) {// 實際項目中建議使用成熟的農歷庫// 這里只做簡單演示const lunarInfo = [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2,// ... 更多農歷數據];// 簡化版的農歷計算,實際項目中請使用完整實現const lunarDay = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十','十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十','廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];// 模擬計算農歷日期,實際使用中請使用準確算法const dayIndex = (year * 10000 + month * 100 + day) % 30;return lunarDay[dayIndex];
}
實際使用示例
下面是在實際項目中使用這個日歷組件的示例:
<template><view class="container"><view class="header"><text class="title">我的日程</text></view><view class="calendar-wrapper"><Calendarv-model="selectedDate":events="eventList"themeColor="#42b983"@change="onDateChange"/></view><view class="event-list"><view class="list-title"><text>{{ formatDate(selectedDate) }}的日程</text></view><view class="empty-tip" v-if="!todayEvents.length"><text>暫無日程安排</text></view><view class="event-item" v-for="(event, index) in todayEvents" :key="index"><view class="event-time">{{ event.time }}</view><view class="event-content"><text class="event-title">{{ event.title }}</text><text class="event-desc">{{ event.description }}</text></view></view></view></view>
</template><script>
import Calendar from '@/components/calendar/calendar.vue';export default {components: {Calendar},data() {return {selectedDate: new Date(),eventList: [{date: '2023-05-15',title: '項目會議',time: '10:00',description: '討論新功能開發計劃'},{date: '2023-05-18',title: '團隊建設',time: '14:00',description: '外出活動'},{date: '2023-05-22',title: '產品發布',time: '09:30',description: '新版本上線'}]};},computed: {todayEvents() {if (!this.selectedDate) return [];const dateStr = this.formatDate(this.selectedDate);return this.eventList.filter(event => event.date === dateStr);}},methods: {onDateChange(date) {console.log('選中日期變化:', date);},formatDate(date) {if (!date) return '';const year = date.getFullYear();const month = (date.getMonth() + 1).toString().padStart(2, '0');const day = date.getDate().toString().padStart(2, '0');return `${year}-${month}-${day}`;}}
};
</script><style lang="scss">
.container {padding: 30rpx;.header {margin-bottom: 30rpx;.title {font-size: 36rpx;font-weight: bold;}}.calendar-wrapper {margin-bottom: 40rpx;}.event-list {background-color: #fff;border-radius: 12rpx;padding: 20rpx;box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);.list-title {font-size: 30rpx;font-weight: bold;margin-bottom: 20rpx;color: #333;}.empty-tip {text-align: center;padding: 40rpx 0;color: #999;}.event-item {display: flex;padding: 20rpx 0;border-bottom: 1px solid #f5f5f5;&:last-child {border-bottom: none;}.event-time {width: 120rpx;color: #666;}.event-content {flex: 1;.event-title {font-size: 28rpx;color: #333;margin-bottom: 6rpx;}.event-desc {font-size: 24rpx;color: #999;}}}}
}
</style>
適配鴻蒙系統
隨著華為鴻蒙系統的普及,我們也需要考慮在鴻蒙系統上的兼容性。好消息是,UniApp已經開始支持鴻蒙系統的開發。要讓我們的日歷組件更好地適配鴻蒙系統,可以考慮以下幾點:
-
遵循鴻蒙設計規范:鴻蒙系統有自己的設計語言和規范,包括字體、顏色、圓角等。我們可以根據鴻蒙的設計規范調整組件樣式。
-
性能優化:鴻蒙系統注重流暢性和低功耗,我們可以減少不必要的渲染和計算,優化日歷組件的性能。
-
手勢適配:確保日歷組件的滑動等手勢操作在鴻蒙系統上響應流暢。
-
分辨率適配:鴻蒙設備的分辨率可能有所不同,確保組件在各種分辨率下都能正常顯示。
-
權限處理:如果日歷組件需要訪問系統日歷數據,需要適配鴻蒙的權限管理機制。
總結與思考
通過本文,我們從零開始實現了一個功能豐富、外觀精致的日歷組件。這個組件具有以下特點:
- 靈活的日期選擇:支持單選和多選模式
- 農歷顯示:可選擇性顯示農歷信息
- 事件標記:能夠在特定日期顯示事件標記
- 自定義主題:支持自定義主題顏色
- 手勢操作:支持左右滑動切換月份
當然,這個日歷組件還可以進一步優化和擴展,比如:
- 添加周視圖、月視圖、年視圖切換功能
- 支持日程管理,添加、編輯、刪除日程
- 增加日程提醒功能
- 支持農歷節日、法定節假日標記
- 優化性能,減少不必要的重新渲染
希望這篇文章對你在 UniApp 開發中實現日歷組件有所幫助。如果有任何問題或建議,歡迎在評論區交流討論!
參考資料
- UniApp 官方文檔:https://uniapp.dcloud.io/
- Vue.js 文檔:https://cn.vuejs.org/
- 農歷計算算法:https://github.com/jjonline/calendar.js
- 鴻蒙開發文檔:https://developer.harmonyos.com/