微信小程序 純js 手寫 時間組件(Component)分類上午、中午、下午、晚上、全天!

產品需求大致:用戶篩選N個藝人,藝人檔期設置的時間分爲5個時間段:上午0 - 11: 59、中午12 - 1: 59、下午2 - 5: 59、晚上6 - 11: 59、全天 00到23:59

效果圖:

 

微信小程序自帶picker :mode = date 組件的時間無法自定義,所以迎合產品需求出發只能手寫一個components 組件,

小程序時間文檔:https://developers.weixin.qq.com/miniprogram/dev/component/picker.html

 

 

html:源碼

<!--components/pickerYMDHM/pickerYMDHM.wxml-->
<picker disabled="{{disabled}}" mode="multiSelector" bindchange="pickerChange" bindcolumnchange="pickerColumnChange" bindcancel="pickerCancel" value="{{pickerIndex}}" range="{{pickerArray}}" range-key="{{'name'}}">
  <text class="riqi">{{d_new_one}}</text>

  <view class='fr' style="display:{{a_none}}">
    <span style="display:{{d_new_one != '迅速找到' ? 'none' : '' }}" class="color_new" data-d="{{d_new_one}}">對應日期下</span>
    有空檔的藝人
  </view>
</picker>

css:源碼

.color_new {
  color: #1cccbe;
}

.fr {
  float: left;
  letter-spacing: 1px;
  /* position: absolute;
  z-index: 1; */
}

.riqi {
  letter-spacing: 1px;
  float: left;
  /* color: #7E8EA6; */
}

.fh_true_2 {
  float: right;
  width: 65px;
  height: 25px;
  margin-top: 0px;
  margin-left: 20px;
}

 

js 源碼

// components/pickerYMDHM/pickerYMDHM.js
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    date: { // 屬性名
      type: null, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
      value: null // 屬性初始值(可選),如果未指定則會根據類型選擇一個
    },
    startDate: {
      type: null, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
      value: null // 屬性初始值(可選),如果未指定則會根據類型選擇一個
    },
    endDate: {
      type: null, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
      value: null // 屬性初始值(可選),如果未指定則會根據類型選擇一個
    },
    disabled: {
      type: null, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
      value: false // 屬性初始值(可選),如果未指定則會根據類型選擇一個
    },
    placeholder: {
      type: null, // 類型(必填),目前接受的類型包括:String, Number, Boolean, Object, Array, null(表示任意類型)
      value: null // 屬性初始值(可選),如果未指定則會根據類型選擇一個
    }
  },

  /**
   * 組件的初始數據
   */
  data: {
    time: ['1', '2', '3'],
    pickerArray: [], //日期控件數據list
    pickerIndex: [], //日期控件選擇的index
    chooseIndex: [], //日期控件確認選擇的index
    chooseArray: [], //日期控件確認選擇後的list
    dateString: '快速查檔期', //頁面顯示日期
    d_new_one: '迅速找到',
  },

  /**
   * U藝站----時間組件的方法列表
   */
  methods: {
    _onInit() {
      let date = new Date();
      if (this.data.date != null) {
        let str = this.data.date;
        str = str.replace(/-/g, "/");
        date = new Date(str);
      }
      let pickerArray = this.data.pickerArray;
      // console.log(date.getFullYear());
      //默認選擇3年內
      let year = [];
      let startDate = date.getFullYear() - 1;
      let endDate = date.getFullYear() + 1;
      if (this.data.startDate != null) {
        //如果存在開始時間,則默認設置結束時間爲2099
        startDate = this.data.startDate;
        endDate = 2099;
      }
      if (this.data.endDate != null && this.data.startDate == null) {
        //如果存在結束時間,不存在開始時間 則默認設置開始時間爲1900
        endDate = this.data.endDate;
        startDate = 1900;
      }
      if (this.data.endDate != null && this.data.startDate != null) {
        endDate = this.data.endDate;
      }
      if (startDate > date.getFullYear() || endDate < date.getFullYear()) {
        this.setData({
          dateString: "默認日期不在時間範圍內"
        })
        return;
      }
      for (let i = startDate; i <= endDate; i++) {
        year.push({
          id: i,
          name: i + "年"
        });
      }
      // console.log(year);
      let month = [];
      for (let i = 1; i <= 12; i++) {
        month.push({
          id: i,
          name: i + "月"
        });
      }
      // console.log(month);
      let dayNum = this._getNumOfDays(date.getFullYear(), date.getMonth() + 1);
      let day = [];
      for (let i = 1; i <= dayNum; i++) {
        day.push({
          id: i,
          name: i + "日"
        });
      }
      // console.log(day);
      // 查檔期時間段:上午0 - 11: 59、中午12 - 1: 59、下午2 - 5: 59、晚上6 - 11: 59、全天
      let time = [
        {
          id:1,
          name: "上午"
        },
        {
          id: 2,
          name: "中午"
        },
        {
          id: 3,
          name: "下午"
        },
        {
          id: 4,
          name: "晚上"
        },
        {
          id: 5,
          name: "全天"
        },
      ];
      // for (let i = 0; i <= 23; i++) {
      //   if(i>=0 && i<12){
      //     time.push({ id: 1, name: "上午"});
      //   } else if (i >= 12 && i < 14) {
      //     time.push({ id: 2, name: "中午" });
      //   } else if (i >= 14 && i < 18) {
      //     time.push({ id: 3, name: "下午" });
      //   } else if (i >= 18 && i < 24) {
      //     time.push({ id: 4, name: "晚上" });
      //   }
      //   // if (i < 10) {
      //   //   time.push({ id: i, name: "0" + i + "時" });
      //   // } else {
      //   //   time.push({ id: i, name: i + "時" });
      //   // }
      // }
      // console.log(time);
      // console.log(division);
      pickerArray[0] = year;
      pickerArray[1] = month;
      pickerArray[2] = day;
      pickerArray[3] = time;
      let mdate = {
        date: date,
        year: date.getFullYear() + '',
        month: date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1 + '',
        day: date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + '',
        time: date.getHours() < 10 ? '0' + date.getHours() : date.getHours() + '',
      }
      mdate.dateString = mdate.year + '-' + mdate.month + '-' + mdate.day + ' ' + mdate.time;
      this.setData({
        pickerArray,
        pickerIndex: [date.getFullYear() - startDate, date.getMonth(), date.getDate() - 1, date.getHours(), date.getMinutes()],
        chooseIndex: [date.getFullYear() - startDate, date.getMonth(), date.getDate() - 1, date.getHours(), date.getMinutes()],
        chooseArray: pickerArray,
        dateString: this.data.placeholder != null ? this.data.placeholder : mdate.dateString
      })
      // console.log(date);
      //設置placeholder屬性後 初始化不返回日期
      if (this.data.placeholder == null) {
        this.triggerEvent('onPickerChange', mdate);
      }
      // console.log(this.data.pickerArray);
      // console.log(this._getNumOfDays(2018, 10));
    },
    /**
     * 
     * 獲取本月天數
     * @param {number} year 
     * @param {number} month 
     * @param {number} [day=0] 0爲本月0最後一天的
     * @returns number 1-31
     */
    _getNumOfDays(year, month, day = 0) {
      return new Date(year, month, day).getDate()
    },
    pickerChange: function (e) {
      // console.log('picker發送選擇改變,攜帶值爲', e.detail.value)
      let indexArr = e.detail.value;
      // console.log(this.data.pickerArray[0][indexArr[0]].id + "\n" + this.data.pickerArray[1][indexArr[1]].id + "\n" + this.data.pickerArray[2][indexArr[2]].id);
      const year = this.data.pickerArray[0][indexArr[0]].id;
      const month = this.data.pickerArray[1][indexArr[1]].id;
      const day = this.data.pickerArray[2][indexArr[2]].id;
      const time = this.data.pickerArray[3][indexArr[3]].id;
      let date = {
        date: new Date(year + '-' + month + '-' + day + ' ' + time),
        year: year + '',
        month: month < 10 ? '0' + month : month + '',
        day: day < 10 ? '0' + day : day + '',
        time: time < 10 ? '0' + time : time + '',
      }
      date.dateString = date.year + '-' + date.month + '-' + date.day + ' ' + date.time;
      // console.log(date);
      let a_slice = date.dateString.slice(0, 11)
      let tow = date.dateString.slice(10, 13)
      // 查檔期時間段:上午0 - 11: 59、中午12 - 1: 59、下午2 - 5: 59、晚上6 - 11: 59、全天
      console.log(tow)
      let that = this
      if (tow == 1) {
        that.setData({
          d_new_one: a_slice + '(上午)',
        })
      } else if (tow == 2) {
        that.setData({
          d_new_one: a_slice + '(中午)',
        })
      } else if (tow == 3) {
        that.setData({
          d_new_one: a_slice + '(下午)',
        })
      } else if (tow == 4) {
        that.setData({
          d_new_one: a_slice + '(晚上)',
        })
      } else if (tow == 5) {
        that.setData({
          d_new_one: a_slice + '(全天)',
        })
      }
      this.setData({
        chooseIndex: e.detail.value,
        chooseArray: this.data.pickerArray,
        dateString: date.dateString.slice(0, 11)
      })
      this.triggerEvent('onPickerChange', date);
    },
    pickerColumnChange: function (e) {
      // console.log('修改的列爲', e.detail.column, ',值爲', e.detail.value);
      var data = {
        pickerArray: this.data.pickerArray,
        pickerIndex: this.data.pickerIndex
      };
      data.pickerIndex[e.detail.column] = e.detail.value;
      if (e.detail.column == 1) {
        let dayNum = this._getNumOfDays(data.pickerArray[0][data.pickerIndex[0]].id, e.detail.value + 1);
        let day = [];
        for (let i = 1; i <= dayNum; i++) {
          day.push({
            id: i,
            name: i + "日"
          });
        }
        if (dayNum < data.pickerIndex[2] + 1) {
          data.pickerIndex[2] = dayNum - 1;
        }
        data.pickerArray[2] = day;
      }
      this.setData(data);
    },
    pickerCancel: function (e) {
      // console.log("取消");
      this.setData({
        pickerIndex: this.data.chooseIndex,
        pickerArray: this.data.chooseArray
      })
    },
  },
  // 以下是舊式的定義方式,可以保持對 <2.2.3 版本基礎庫的兼容
  attached() {
    // 在組件實例進入頁面節點樹時執行
    // 在組件實例進入頁面節點樹時執行
    // this._onInit();
  },
  ready() {
    console.log('進入ready外層節點=', this.data.date);
    this._onInit();
  },
  // 以下爲新方法 >=2.2.3
  lifetimes: {
    attached() {
      // 在組件實例進入頁面節點樹時執行
      // this._onInit();
    },
    detached() {
      // 在組件實例被從頁面節點樹移除時執行
    },
    ready() {
      this._onInit();
    }
  }
})

js 關鍵點在於 hour 小時這裏的處理  日期選擇器:mode = date 回填的數據是0小時到59分23小時59分

定義一個自己想要的數組  ,在pickerArray[hour]下插入, 拿到數據在this.setdata

這裏要注意

//設置placeholder屬性後 初始化不返回日期

if (this.data.placeholder == null) {

this.triggerEvent('onPickerChange', mdate);

}

      let time = [
        {
          id:1,
          name: "上午"
        },
        {
          id: 2,
          name: "中午"
        },
        {
          id: 3,
          name: "下午"
        },
        {
          id: 4,
          name: "晚上"
        },
        {
          id: 5,
          name: "全天"
        },
      ];

然後在pickerChange 的點擊事件下就可以拿到下標,拿到下標就意味着可以區分是上午還是下午還是全天

點擊之後的下標如圖:(小程序代碼片段截圖)

 

 

真實項目截圖:

 

 

 

覺得我寫的對你有幫助幫忙點個讚唄~~~~~~

ps:這裏有一個bug一定要注意一下 ios時間機制格式 “YYYY-MM-DD“ 時間格式中的“-”替換成 “/” 否則微信小程序 ios端是不會顯示時間的,注意:date是字符串類型。

 

代碼片段:https://developers.weixin.qq.com/s/8HlcEbmz77cH

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章