原生微信小程序?qū)崿F(xiàn)打卡日歷組件

背景:最近接了個外包,其中有個打卡功能,里面包含了一個日歷,甲方要求百分百還原,閑暇之余就擼了一下,下面是效果圖 源碼地址 https://github.com/chenxuba/xx-calendar 求star ?
image.png
分析:
  • 要求左右箭頭可切換上下月;
  • 需要展示農(nóng)歷日歷;
  • 點擊日期拿到年月日(yyyy-mm-dd)
  • 樣式一比一還原
想法??:網(wǎng)上都沒一毛一樣的組件,那還想個der,自己擼一個啊~
組件我起名:xx-calendar
  • 第一步:在小程序components目錄下新建一個組件xx-calendar
image.png
  • 第二步:在你想要引入的頁面的xxx.json文件里引入該組件
{
  "usingComponents": {
      "xx-calendar":"../../components/xx-calendar/xx-calendar"
  }
}
  • 第三步:在xxx.wxml里使用該組件
<xx-calendar></xx-calendar>
  • 第三步:前端寫頁面,啥都不要想,先擼樣式,靜態(tài)頁面擼起走~
  • 3.1 先擼頭部
image.png
  • xx-calendar.wxml
<!--components/xx-calendar/xx-calendar.wxml-->
<!-- 頭部 -->
<view class="title-wrap">
    <view class="change-date">
        <view class="prev">
            <image src="./prev.png" mode="" />
        </view>
        <view class="year-mouth">
            2023年 1月
        </view>
        <view clstyle="next">
            <image src="./next.png" mode="" />
        </view>
    </view>
    <view class="week">
        <text>日</text>
        <text>一</text>
        <text>二</text>
        <text>三</text>
        <text>四</text>
        <text>五</text>
        <text>六</text>
    </view>
</view>
<!-- 日期 -->
<view class="date-wrap">
    <!-- 上個月日期 -->
    <view class="mouth-date last-mouth">
        <text class="day-text">29</text>
        <text class="day-nongli">十五</text>
        <text class="day-dot"></text>
    </view>
    <view class="mouth-date last-mouth">
        <text class="day-text">30</text>
        <text class="day-nongli">十六</text>
        <text class="day-dot"></text>
    </view>
    <view class="mouth-date last-mouth">
        <text class="day-text">31</text>
        <text class="day-nongli">十七</text>
        <text class="day-dot"></text>
    </view>
    <!-- 當(dāng)月日期 -->
    <view class="mouth-date current-mouth" wx:for="{{31}}">
       <view class="day-box {{index==0?'active':''}}">
        <text class="day-text {{index==2||index==4||index==6||index==8?'color':''}}">{{index+1}}</text>
        <text class="day-nongli">十八</text>
        <text class=" {{index==2||index==4||index==6||index==8?'day-dot':'not-dot'}}"></text>
       </view>
    </view>
    <!-- 下個月日期 -->
    <view class="mouth-date next-mouth">
        <text class="day-text">1</text>
        <text class="day-nongli">十五</text>
        <text class="day-dot"></text>
    </view>
</view>
  • xx-calendar.wxss
/* components/xx-calendar/xx-calendar.wxss */
/* 頭部樣式start */
.title-wrap{
    background-color: #fff;
    padding-top: 20rpx;
    border-bottom: 1px solid #D4DBDC;
    padding-bottom: 10rpx;
}
.change-date{
    display: flex;
    justify-content: center;
    align-items: center;
}
.change-date image{
    width: 50rpx;
    height: 50rpx;
    transform: scale(1.5);
    display: flex;
}
.year-mouth{
    margin: 0 60rpx;
}
.week{
    display: flex;
    justify-content: space-between;
    font-size: 24rpx;
    margin-top: 30rpx;
    color: #1F1F1F;
}
.week text{
    flex: 1;
    text-align: center;
}
/* 頭部樣式end */
/* 日期區(qū)域樣式start */
.date-wrap{
    height: 500rpx;
    background-color: #F8F9F9;
    display: flex;
    flex-wrap: wrap;
}
.mouth-date{
    display: flex;
    font-size: 24rpx;
    flex-direction: column;
    align-items: center;
    width: calc(100% / 7);
    border-bottom: 1rpx solid rgb(229, 234, 235);
    padding-top: 10rpx;
}
.last-mouth text,.next-mouth text{
    opacity: 0;
}
.mouth-date .day{
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #1F1F1F;

}
.mouth-date  .day-nongli{
    font-size: 18rpx;
    color: #888888;
    margin-bottom: 6rpx;
}
.mouth-date .color{
    color: #8096F0;
}
.mouth-date  .day-dot{
    width: 8rpx;
    height: 8rpx;
    border-radius: 50%;
    background-color: #8096F0;
}
.mouth-date .day-box{
    border-radius: 10rpx;
    width: 80rpx;
    padding-top: 6rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.mouth-date .active{
    background-color: #A1D7EE;
}
.mouth-date .active text{
    color: #fff;
}
.mouth-date .active .day-text{
    font-weight: 600;
}
.not-dot{
    width: 8rpx;
    height: 8rpx;
}
  • 樣式寫完就是下面這個樣子了,注意:??css和dom后面還會根據(jù)實際情況微調(diào)
image.png
  • 選中狀態(tài)和已打卡樣式都暫時是根據(jù)索引模擬出來的,農(nóng)歷日期也不對
  • 下面就來寫js,獲取上個月日期數(shù)組、當(dāng)月日期數(shù)組下個月日期數(shù)組
  • 農(nóng)歷暫時先放一放
  • 下面先來寫三個方法,分別來 獲取上個月日期、當(dāng)月日期下個月日期
  • xx-calendar.js
  • 點定義好本月的年月,渲染日歷頭部,并且把星期也換成變量,即:
data:{
   year: new Date().getFullYear(),
   month: new Date().getMonth() + 1,
   weeksArr: ['日', '一', '二', '三', '四', '五', '六'],
}
  • 在日歷dom處渲染這三個變量
image.png
image.png
  • 下面在data里再定義幾個變量,用來存儲日期
data:{
        nowMonth: new Date().getMonth() + 1, //本月是幾月
        nowDay: new Date().getDate(), //本月當(dāng)天的日期
        lastMonthDays: [], //上一個月
        nowMonthDays: [], //本月 
        nextMonthDays: [], //下一個月
}
  • 在methods里定義三個方法
 /**
     * 組件的方法列表
     */
    methods: {
        /** 獲取上個月日期 */
        getLastMonthDays(year,month){},
       /** 獲取當(dāng)月日期 */
        getNowMonthDays(year, month) {},
        /** 獲取下個月日期 */
        getNextMonthDays(year, month) {},
    }
  • 為了方便調(diào)用,寫一個總方法,一并調(diào)用這三個方法,并在ready里調(diào)用這個總方法,傳入year和month,邏輯需要,還要寫一個獲取當(dāng)月天數(shù)的方法
 /**
     * 組件的方法列表
     */
    methods: {
         //獲取當(dāng)月天數(shù)
        getThisMonthDays(year, month) {
            return new Date(year, month, 0).getDate();
        },
        /** 總方法 */
        //創(chuàng)建日期
        createDays(year, month) {
            this.getLastMonthDays(year, month)
            this.getNowMonthDays(year, month)
            this.getNextMonthDays(year, month)
        },
        /** 獲取上個月日期 */
        getLastMonthDays(year, month) {},
       /** 獲取當(dāng)月日期 */
        getNowMonthDays(year, month) {},
        /** 獲取下個月日期 */
        getNextMonthDays(year, month) {},
    },
    ready(){
        let { year,month } = this.data
        this.createDays(year,month)
    }

  • 接下來,先寫獲取上個月日期的方法,如下:
/** 獲取上個月日期 */
        getLastMonthDays(year, month) {
            let nowMonthFirstDays = new Date(year, month - 1, 1).getDay()
            let lastMonthDays = []
            if (nowMonthFirstDays) { //判斷當(dāng)月的第一天是不是星期天
                //上個月顯示多少天
                let lastMonthNums = month - 1 < 0 ? this.getThisMonthDays(year - 1, 12) : this.getThisMonthDays(year, month - 1); //判斷是否會跨年
                //上個月從幾號開始顯示
                for (let i = lastMonthNums - nowMonthFirstDays + 1; i <= lastMonthNums; i++) {
                    let time = new Date(year, month - 2, i).toLocaleDateString() //對應(yīng)的時間
                    lastMonthDays.push({
                        date: i, //幾號
                        week: this.data.weeksArr[new Date(year, month - 2, i).getDay()], //星期幾
                        time,
                        isNowMonthDay: ''
                    });
                }
            }
            this.setData({
                lastMonthDays
            })
            console.log(lastMonthDays);
        },
  • 打印結(jié)果可以看到 ,已經(jīng)拿到上個月的日期已經(jīng)對應(yīng)的數(shù)據(jù)
  • ??:安卓手機上會存在bug,寫法造成的,解決方法我放到文章最后
image.png
  • 上個月的日期已經(jīng)拿到了,下面可以在dom里渲染這個【lastMonthDays】數(shù)組了
image.png
  • 下面在編寫獲取當(dāng)月日期的方法
 getNowMonthDays(year, month) {
            let {
                nowMonth,
                nowDay
            } = this.data
            let nowMonthDays = []
            let days = this.getThisMonthDays(year, month); //獲取當(dāng)月的天數(shù)
            for (let i = 1; i <= days; i++) {
                let d = new Date(year, month - 1, i)
                let years = d.getFullYear()
                let months = d.getMonth() + 1
                let day = d.getDate()
                let time = `${years+'/'+months +'/'+day}` // 2023/3/3
                nowMonthDays.push({
                    date: i, //幾號
                    week: this.data.weeksArr[new Date(year, month - 1, i).getDay()], //星期幾
                    time,
                    color: false, //為已打卡日期樣式做準(zhǔn)備
                    day, //后面會改成農(nóng)歷
                    isNowMonthDay: (month == nowMonth && i == nowDay) ? "isNowMonthDay" : ""
                });
            }
            this.setData({
                nowMonthDays
            })
            console.log(nowMonthDays);
        },
  • 打印可以拿到當(dāng)月的所有日期數(shù)組,主要圈出來的,默認(rèn)選中當(dāng)天的日期
image.png
  • 日期數(shù)組拿到了,當(dāng)天的選中狀態(tài)條件也拿到了,下面微調(diào)下dom,渲染【nowMonthDays】和完善默認(rèn)選中條件


    image.png
  • 在接下來,編寫獲取下個月的日期方法
/** 獲取下個月日期 */
        getNextMonthDays(year, month) {
            let {
                lastMonthDays,
                nowMonthDays,
            } = this.data
            let nextMonthDays = []
            let nextMonthNums = (lastMonthDays.length + nowMonthDays.length) > 35 ? 42 - (lastMonthDays.length + nowMonthDays.length) : 35 - (lastMonthDays.length + nowMonthDays.length) //下個月顯示多少天
            let nowYear = (parseInt(month) + 1) > 12 ? year + 1 : year //下一個月的年份
            let nowMonth = (parseInt(month) + 1) > 12 ? 1 : parseInt(month) + 1 //下一個月的月份
            if (nextMonthNums) { //判斷當(dāng)前天數(shù)是否大于零
                for (let i = 1; i <= nextMonthNums; i++) {
                    let time = new Date(year, month - 1, i).toLocaleDateString()
                    nextMonthDays.push({
                        date: i, //幾號
                        week: this.data.weeksArr[new Date(nowYear, nowMonth - 1, i).getDay()], //星期幾
                        time,
                        isNowMonthDay: ''
                    });
                }
            }
            this.setData({
                nextMonthDays
            })
            console.log(nextMonthDays)
        },
  • 打印數(shù)組
image.png
  • 下面渲染這個【nextMonthDays】數(shù)組
image.png
  • 還沒渲染農(nóng)歷的樣子,就是下圖
image.png
  • 下面渲染農(nóng)歷,需要用到一個公共方法,這個方法很復(fù)雜,也很長,就不再這里展示了,你可以訪問我的github倉庫下載源碼獲取這個方法. https://github.com/chenxuba/xx-calendar
  • 頁面內(nèi)引入這個js
import calendarFormatter from "./index";
  • 需要修改的是獲取當(dāng)月日期的這個方法,上下月都不展示,就不修改其他倆方法了,如果你需要請自行二開
 getNowMonthDays(year, month) {
            let {
                nowMonth,
                nowDay
            } = this.data
            let nowMonthDays = []
            let days = this.getThisMonthDays(year, month); //獲取當(dāng)月的天數(shù)
            for (let i = 1; i <= days; i++) {
                let d = new Date(year, month - 1, i)
                let years = d.getFullYear()
                let months = d.getMonth() + 1
                let day2 = d.getDate()
                let time = `${years+'/'+months +'/'+day2}` // 2023/3/3
                let timer = time.replace(/\//g, "-")
                let timer2 = timer.split('-')
                var day = calendarFormatter.solar2lunar(timer2[0], timer2[1], timer2[2]);
                let newdate
                if (day.IDayCn == '初一') {
                    newdate = day.IMonthCn
                } else {
                    newdate = day.IDayCn
                }
                nowMonthDays.push({
                    date: i, //幾號
                    week: this.data.weeksArr[new Date(year, month - 1, i).getDay()], //星期幾
                    time,
                    color: false,
                    day: newdate,
                    isNowMonthDay: (month == nowMonth && i == nowDay) ? "isNowMonthDay" : ""
                });
            }
            this.setData({
                nowMonthDays
            })
            console.log(nowMonthDays);
        },
嗯~實現(xiàn)了
image.png
  • 下面在實現(xiàn)點擊左右箭頭切換月份
image.png
/** 切換月份 */
        changeMonthFun(e){
            let {
                year,
                month
            } = this.data
            let type = e.currentTarget.dataset.type //類型
            if (type == 'prev') { //上一個月
                year = month - 1 > 0 ? year : year - 1
                month = month - 1 > 0 ? month - 1 : 12
            } else { //next 下個月
                year = (parseInt(month) + 1) > 12 ? year + 1 : year
                month = (parseInt(month) + 1) > 12 ? 1 : parseInt(month) + 1
            }
            this.setData({
                year,
                month,
            })
            this.createDays(year, month)
        }
  • 這樣就實現(xiàn)了切換月份
image.png
  • 有點小瑕疵,不打緊,之前寫靜態(tài)頁面的時候固定高度了,注釋掉就可以了
image.png
  • 一切正常
image.png
  • 下面在實現(xiàn)點擊日期,拿到當(dāng)前年月日
selectDate(e){
            let type = e.currentTarget.dataset.type //選擇的時間類型
            let index = e.currentTarget.dataset.index //選擇的下標(biāo)
            let date = e.currentTarget.dataset.item.time //選擇的下標(biāo)
            let selectDate = date.replace(/\//g, "-")
            console.log("選擇的時間", selectDate)
            // 自定義事件,父組件調(diào)用,回調(diào) 選擇的時間selectDate
            this.triggerEvent('selectDate', selectDate)
             //將選擇的時間類型的 isNowMonthDay 全改為''
             this.data[type]?.forEach(item => {
                item.isNowMonthDay = ''
            })
            this.data[type]?.forEach((item, idx) => {
                if (index == idx) {
                    item.isNowMonthDay = (item.time == new Date().toLocaleDateString() ? "isNowMonthDay" : "isNotNowMonthDay"); //判斷當(dāng)前選中的日期是否是當(dāng)前時間
                } else {
                    item.isNowMonthDay = ''
                }
            })
            this.setData({
                [type]: this.data[type],
            })
        },
image.png
  • 最后實現(xiàn) 已打卡日期的樣式展示,要從父組件接收一個已打卡日期數(shù)組,通過對比當(dāng)月日期,來動態(tài)改變之前備用的color字段

  • 先接收一個數(shù)組
  /**
     * 組件的屬性列表
     */
    properties: {
        use_date_arr:{
            type:Array,
            value:[]
        }
    },
  • 然后修改getNowMonthDays方法
 this.data.use_date_arr.forEach(ele => {
                ele = ele.replace(/\-/g, "/")
                nowMonthDays.forEach(item => {
                    if (ele == item.time) {
                        console.log(item);
                        item.color = true
                    }
                })
            })
image.png
  • 然后在父組件傳入這個use_date_arr數(shù)組
data: {
    use_date_arr:['2023-3-1','2023-3-2','2023-3-3','2023-3-5','2023-3-8']
  },
<xx-calendar use_date_arr="{{use_date_arr}}"></xx-calendar>
  • 最后的效果
image.png
  • 取消高度導(dǎo)致圓點沒距離了,稍微微調(diào)下
image.png
  • 搞定
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容