>위챗 애플릿 >미니 프로그램 개발 >WeChat 애플릿 예: 사용자 정의 날짜 제어를 구현하는 코드

WeChat 애플릿 예: 사용자 정의 날짜 제어를 구현하는 코드

不言
不言원래의
2018-08-21 17:34:335528검색

이 기사는 특정 참조 값이 있는 사용자 정의 날짜 제어를 구현하는 코드인 WeChat 애플릿의 예를 제공합니다. 도움이 필요한 친구가 이를 참조할 수 있기를 바랍니다.

최근에 WeChat 애플릿을 조사 중인데 Maoyan 앱에서 날짜를 선택하는 것과 유사한 사용자 정의 날짜 기능을 구현해야 합니다. 날짜를 일, 주, 월, 연도별로 맞춤 설정할 수 있습니다. 이런 이유로 특별히 A 컴포넌트는 도움이 필요한 친구들이 참고할 수 있도록 제공됩니다.
제가 사용하는 프레임워크는 wepy이므로 컴포넌트 구조도 wepy 코드 구조입니다.

일반 소개:
1. 일일 달력 제어는 Pole 달력 플러그인을 사용합니다. 자세한 내용은 https://github.com/czcaiwj/calendar를 참조하세요.
2. 자세한 내용은 내 다른 공유를 참조하세요: https://www.jianshu.com/p/e07b7cf5e494;
3. 특정 구현에 대해서는 주별로 선택했습니다. 다른 기사 공유: https://www.jianshu.com/p/5112df795162; 이 기사의 onLoad() 메서드에도 구현되어 있습니다.
4. 이 구성 요소의 기본 시간은 2017년부터이며 실제 필요에 따라 조정될 수도 있습니다.

성취 효과:

코드는 다음과 같습니다.

<style type="less">
    .home {
        height: 100%;
        .calendar-header {
            font-size: large;
            color: #406BF8;
         }
        .calendar-board {
            color: #406BF8;
        }
        .week_year_style {
            font-size: 30 rpx;
            padding: 20 rpx 15 rpx;
            text-align: center;
        }
        .week_selectyear_style {
            background-color: #fff;
            color: #406BF8;
        }
        .calendar {
            background-color: #fcfcfc;
            //padding-top: 10px;
        }
    }
</style>
<template>
    <view class="home page">
        <i-tabs current="{{ currentTab }}" color="#406BF8" bindchange="handleChangeTab">
            <i-tab key="按日" title="按日"></i-tab>
            <i-tab key="按周" title="按周"></i-tab>
            <i-tab key="按月" title="按月"></i-tab>
            <i-tab key="按年" title="按年"></i-tab>
            <i-tab key="自定义" title="自定义"></i-tab>
        </i-tabs>
        <view hidden="{{currentTab != &#39;按日&#39;}}" style="margin-top: 30rpx">
            <calendar cell-size="40"
                      show-more-days="true"
                      lunar="true"
                      weeks-type="cn"
                      calendar-style="calendar"
                      header-style="calendar-header"
                      board-style="calendar-board"
                      days-color="{{days_style}}"
                      start-date="2017-01"
                      end-date="2018-08"
                      binddayClick="dayClick"
                      bindnextMonth="next"
                      bindprevMonth="prev"
            />
        </view>
        <view hidden="{{currentTab != &#39;按周&#39;}}">
            <view style="display: flex">
                <view style="width: 160rpx;background-color: #f6f6f6;border-right: 1rpx solid #e6e6e6">
                    <block wx:for="{{yearArray}}" wx:for-item="item" wx:key="item">
                        <view class="week_year_style {{weeksYears==item?&#39;week_selectyear_style&#39;:&#39;&#39;}}"
                              bindtap=&#39;changeWeekYear({{item}})&#39;>{{item + &#39;年&#39;}}
                        </view>
                    </block>
                </view>
                <scroll-view scroll-y style="height: 600px;">
                    <i-cell-group>
                        <block wx:for="{{weeksArray[weeksYears]}}" wx:for-item="category" wx:key="category">
                            <i-cell title="{{category.weeks}}" bindtap="handleWeeksChange(&#39;{{index}}&#39;)">
                                <i-icon wx:if="{{category.select}}" type="right" size="20" color="#406BF8"
                                        slot="footer"/>
                            </i-cell>
                        </block>

                    </i-cell-group>
                </scroll-view>
            </view>
        </view>

        <view hidden="{{currentTab != &#39;按月&#39;}}">
            <view style="display: flex">
                <view style="width: 160rpx;background-color: #f6f6f6;border-right: 1rpx solid #e6e6e6">
                    <block wx:for="{{yearArray}}" wx:for-item="item" wx:key="item">
                        <view class="week_year_style {{monthYear==item?&#39;week_selectyear_style&#39;:&#39;&#39;}}"
                              bindtap=&#39;changeMonthYear({{item}})&#39;>{{item + &#39;年&#39;}}
                        </view>
                    </block>

                </view>
                <scroll-view scroll-y style="height: 600px;">
                    <i-cell-group>
                        <block wx:for="{{monthYear==year?currentMonthArray:fullMonthArray}}" wx:for-item="category"
                               wx:key="*this">
                            <i-cell title="{{category+&#39;月&#39;}}" bindtap="handleMonthChange(&#39;{{category}}&#39;)">
                                <i-icon wx:if="{{category==selectMonth}}" type="right" size="20" color="#406BF8"
                                        slot="footer"/>
                            </i-cell>
                        </block>

                    </i-cell-group>
                </scroll-view>
            </view>
        </view>

        <view hidden="{{currentTab != &#39;按年&#39;}}">
            <i-cell-group>
                <block wx:for="{{yearArray}}" wx:for-item="category" wx:key="category">
                    <i-cell title="{{category+&#39;年&#39;}}" bindtap="handleYearChange(&#39;{{category}}&#39;)">
                        <i-icon wx:if="{{category==selectYear }}" type="right" size="20" color="#406BF8" slot="footer"/>
                    </i-cell>
                </block>

            </i-cell-group>
        </view>

        <view hidden="{{currentTab != &#39;自定义&#39;}}" style="margin-top: 30rpx">
            <calendar cell-size="40"
                      show-more-days="true"
                      lunar="true"
                      weeks-type="cn"
                      calendar-style="calendar"
                      header-style="calendar-header"
                      board-style="calendar-board"
                      days-color="{{define_days_style}}"
                      start-date="2017-01"
                      end-date="2018-08"
                      binddayClick="dayClick_define"
                      bindnextMonth="next_define"
                      bindprevMonth="prev_define"

            />
        </view>

    </view>
</template>
<script>
    import wepy from &#39;wepy&#39;;

    const MONTHS = [&#39;Jan.&#39;, &#39;Feb.&#39;, &#39;Mar.&#39;, &#39;Apr.&#39;, &#39;May.&#39;, &#39;June.&#39;, &#39;July.&#39;, &#39;Aug.&#39;, &#39;Sept.&#39;, &#39;Oct.&#39;, &#39;Nov.&#39;, &#39;Dec.&#39;];

    export default class TabsContent extends wepy.component {
        props = {
            openDateModal: {
                type: Boolean,
                default: false,
                twoWay: true
            },
            dateSelect: {
                type: String,
                default: &#39;&#39;,
                twoWay: true
            },
            dateFilter: {
                type: String,
                default: &#39;&#39;,
                twoWay: true
            },
            filterWeekArray: {
                type: String,
                default: &#39;&#39;,
                twoWay: true
            },
            filterWeekSelect: {
                type: String,
                default: &#39;&#39;,
                twoWay: true
            }
        };
        data = {
            currentTab: &#39;按日&#39;,  //Tabs页切换

            year: new Date().getFullYear(),      // 年份
            month: new Date().getMonth() + 1,    // 月份
            day: new Date().getDate(),
            str: MONTHS[new Date().getMonth()],  // 月份字符串

            days_style: [{month: &#39;current&#39;, day: new Date().getDate(), color: &#39;#fff&#39;, background: &#39;#eb4986&#39;}],  //按日选中日期样式
            selectDate: [],   //按日选择的日期

            yearArray: [],  //从2017年起至今
            weeksYears: new Date().getFullYear(),  //按周选择了哪一年
            weeksArray: {},   //从2017年起至今的所有周
            selectWeekArray: [],   //选择的周

            fullMonthArray: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
            currentMonthArray: [],  //今年过了几个月
            monthYear: new Date().getFullYear(),  //按月选择了哪一年
            selectMonth: 0,  //按月选择了哪一月

            selectYear: 0,  //按年选择了哪一年

            define_days_style: [{month: &#39;current&#39;, day: new Date().getDate(), color: &#39;#fff&#39;, background: &#39;#eb4986&#39;}],  //自定义日期格式
            selectDate_define: []


        };

        methods = {
            handleChangeTab({detail}) {
                this.currentTab = detail.key
                this.dateFilter = this.currentTab
            },

            dayClick: function (event) {
                let style = (event.detail.year == this.year && event.detail.month == this.month) ?
                    [{month: &#39;current&#39;, day: new Date().getDate(), color: &#39;#fff&#39;, background: &#39;#eb4986&#39;},
                        {month: &#39;current&#39;, day: event.detail.day, color: &#39;#fff&#39;, background: &#39;#406BF8&#39;}] :
                    [{month: &#39;current&#39;, day: event.detail.day, color: &#39;#fff&#39;, background: &#39;#406BF8&#39;}]
                this.days_style = style
                this.selectDate = [event.detail.year, event.detail.month, event.detail.day]
                this.openDateModal = false
                this.dateFilter = this.currentTab
                this.dateSelect = [event.detail.year, event.detail.month, event.detail.day]
            },
            next: function (event) {
                if (event.detail.currentYear == this.year && event.detail.currentMonth == this.month)
                    this.days_style = [{
                        month: &#39;current&#39;,
                        day: new Date().getDate(),
                        color: &#39;#fff&#39;,
                        background: &#39;#eb4986&#39;
                    }]
                else this.days_style = [vent.detail.year, event.detail.month, event.detail.day]
            },
            prev: function (event) {
                this.days_style = []
            },

            changeWeekYear(year) {
                this.weeksYears = year
            },
            handleWeeksChange(weekIndex) {
                this.weeksArray[this.weeksYears][weekIndex].select = !this.weeksArray[this.weeksYears][weekIndex].select

                if (this.selectWeekArray[this.weeksYears]) {
                    let bool = this.selectWeekArray[this.weeksYears].some(index => index == weekIndex)
                    if (bool) { //真 已存在 delete
                        //if(this.selectWeekArray[this.weeksYears].length>1)
                        this.selectWeekArray[this.weeksYears].remove(weekIndex)
                    } else {   //假  push
                        this.selectWeekArray[this.weeksYears].push(weekIndex)
                        this.selectWeekArray[this.weeksYears].sort()
                    }
                } else {
                    let temp = {}
                    temp[this.weeksYears] = []
                    let a = [weekIndex]
                    temp[this.weeksYears] = a
                    this.selectWeekArray = temp
                }
                this.filterWeekSelect = this.selectWeekArray  //回调到父级页面
            },

            changeMonthYear(year) {
                this.monthYear = year
            },
            handleMonthChange(month) {
                this.selectMonth = month
                this.openDateModal = false
                this.dateFilter = this.currentTab
                this.dateSelect = [this.monthYear, this.selectMonth]
            },

            handleYearChange(year) {
                this.selectYear = year
                this.openDateModal = false
                this.dateFilter = this.currentTab
                this.dateSelect = [year]
            },

            dayClick_define: function (event) {
                let style = []
                if (this.selectDate_define.length == 0) {  //第一次点击
                    this.selectDate_define.push([event.detail.year, event.detail.month, event.detail.day])
                    if (event.detail.year == this.year && event.detail.month == this.mounth) {
                        style = [{month: &#39;current&#39;, day: new Date().getDate(), color: &#39;#fff&#39;, background: &#39;#eb4986&#39;},
                            {month: &#39;current&#39;, day: event.detail.day, color: &#39;#fff&#39;, background: &#39;#406BF8&#39;}]
                    }
                    this.define_days_style = style
                } else if (this.selectDate_define.length == 1) {   //选中第二个日期就关闭页面
                    this.selectDate_define.push([event.detail.year, event.detail.month, event.detail.day])
                    this.define_days_style.push({
                        month: &#39;current&#39;,
                        day: event.detail.day,
                        color: &#39;#fff&#39;,
                        background: &#39;#406BF8&#39;
                    })

                    this.openDateModal = false
                    this.dateFilter = this.currentTab
                    this.dateSelect = this.selectDate_define
                } else {   //重新自定义日期
                    this.selectDate_define = [[event.detail.year, event.detail.month, event.detail.day]]
                    style = [{month: &#39;current&#39;, day: new Date().getDate(), color: &#39;#fff&#39;, background: &#39;#eb4986&#39;},
                        {month: &#39;current&#39;, day: event.detail.day, color: &#39;#fff&#39;, background: &#39;#406BF8&#39;}]
                    this.define_days_style = style
                }
            },
            next_define: function (event) {
                if (event.detail.currentYear == this.year && event.detail.currentMonth == this.month)
                    this.define_days_style = [{
                        month: &#39;current&#39;,
                        day: new Date().getDate(),
                        color: &#39;#fff&#39;,
                        background: &#39;#eb4986&#39;
                    }]
                else this.define_days_style = [event.detail.year, event.detail.month, event.detail.day]
            },
            prev_define: function (event) {
                this.define_days_style = []
            },

        };

        onLoad() {
            let currentYear = new Date().getFullYear()
            let currentMonth = new Date().getMonth() + 1
            for (var i = currentYear; i >= 2017; i--) {
                this.yearArray.push(i)
            }
            for (var i = currentMonth; i >= 1; i--) {
                this.currentMonthArray.push(i)
            }

            let weeksArray = {}   //计算2017年至今的所有周
            for (var i = 0; i <= this.yearArray.length; i++) {
                let index = 1;
                let temp = []
                if (i == 0) {  //今年
                    for (let i of createWeeks(this.yearArray[i])) {
                        let start = i[0],
                            end = i[1];
                        if (end <= new Date().getTime() || (start <= new Date().getTime() && end >= new Date().getTime())) {
                            let a = start <= new Date().getTime() && end >= new Date().getTime() ?
                                &#39;第&#39; + formatDig(index++) + &#39;周(&#39; + formatDate(start) + &#39;日-&#39; + formatDate(end) + &#39;日)&#39; + &#39; 本周&#39; :
                                &#39;第&#39; + formatDig(index++) + &#39;周(&#39; + formatDate(start) + &#39;日-&#39; + formatDate(end) + &#39;日)&#39;
                            temp.push({&#39;weeks&#39;: a, &#39;select&#39;: false})
                        }
                    }
                } else {
                    for (let i of createWeeks(this.yearArray[i])) {
                        let start = i[0],
                            end = i[1];
                        let a = &#39;第&#39; + formatDig(index++) + &#39;周(&#39; + formatDate(start) + &#39;日-&#39; + formatDate(end) + &#39;日)&#39;
                        temp.push({&#39;weeks&#39;: a, &#39;select&#39;: false})
                    }
                }
                if (this.yearArray[i] != undefined) {
                    weeksArray[this.yearArray[i]] = temp.reverse();
                }
            }
            this.weeksArray = weeksArray
            this.filterWeekArray = weeksArray

        }
    }

    function formatDig(num) {
        //return num>9?&#39;&#39;+num:&#39;0&#39;+num;
        return num;
    }

    function formatDate(mill) {
        var y = new Date(mill);
        let raws = [
            //y.getFullYear(),
            formatDig(y.getMonth() + 1),
            formatDig(y.getDate()),
            //y.getDay()||7  //获取星期几
        ];
        //let format=[&#39;年&#39;,&#39;月&#39;,&#39;日 星期&#39;];
        let format = [&#39;月&#39;, &#39;日&#39;];
        return String.raw({raw: raws}, ...format);
    }

    function* createWeeks(year) {
        const ONE_DAY = 24 * 3600 * 1000;
        let start = new Date(year, 0, 1),
            end = new Date(year, 11, 31);
        let firstDay = start.getDay() || 7,
            lastDay = end.getDay() || 7;
        let startTime = +start,
            endTime = startTime + (7 - firstDay) * ONE_DAY,
            _endTime = end - (7 - lastDay) * ONE_DAY;
        yield [startTime, endTime];
        startTime = endTime + ONE_DAY;
        endTime = endTime + 7 * ONE_DAY;
        while (endTime < _endTime) {
            yield [startTime, endTime];
            startTime = endTime + ONE_DAY;
            endTime = endTime + 7 * ONE_DAY;
        }
        yield [startTime, +end];
    }

    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
</script>

관련 권장 사항:

WeChat 미니 프로그램 예: 맞춤형 네비게이션 바 구현 방법

미니 프로그램 예 : 미니 데이터 로딩을 위한 프로그램 페이징 구현 코드

위 내용은 WeChat 애플릿 예: 사용자 정의 날짜 제어를 구현하는 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.