微信小程序之自定義倒計時組件

開頭

  • 最近寫小程序寫上癮了,業務上須要實現一個倒計時的功能,考慮到可拓展以及使用方便,便將其封裝成組件(寫習慣了JSX不得不吐槽小程序自定義組件的繁瑣)

需求

  • 可配置倒計時的時間
  • 倒計時結束後執行事件
  • 可配置倒計時時間的格式

步驟

  • 先定義自定義組件的properties,這裏有兩個父組件傳給該倒計時組件的參數target倒計時的時間,format倒計時時間的格式
properties: {
    target: {
      type: String,
    },
    format: {
      type: Function,
      default: null
    }
},
  • 定義組件生命週期函數
lifetimes: {
    attached() {
      //組件建立時
      this.setData({
        lastTime: this.initTime(this.properties).lastTime,  //根據 target 初始化組件的lastTime屬性
      }, () => {
        //開啓定時器
        this.tick();
        //判斷是否有format屬性 若是設置按照自定義format處理頁面上顯示的時間 沒有設置按照默認的格式處理
        if (typeof this.properties.format === 'object') {
          this.defaultFormat(this.data.lastTime)
        }
      })
    },

    detached() {
      //組件銷燬時清除定時器 防止爆棧
      clearTimeout(timer);
    },
},
微信小程序自定義組件的生命週期指的是指的是組件自身的一些函數,這些函數在特殊的時間點或遇到一些特殊的框架事件時被自動觸發。其中,最重要的生命週期是 created attached detached ,包含一個組件實例生命流程的最主要時間點。具體微信自定義組件學習參考 官方文檔
  • 定義組件自身的狀態
/**
 * 組件的初始數據
*/
data: {
    d: 0, //天
    h: 0, //時
    m: 0, //分
    s: 0, //秒
    result: '',  //自定義格式返回頁面顯示結果
    lastTime:''  //倒計時的時間錯
},
  • 組件自身的方法
methods: {
    //默認處理時間格式
    defaultFormat: function(time) {
      const day = 24 * 60 * 60 * 1000
      const hours = 60 * 60 * 1000;
      const minutes = 60 * 1000;

      const d = Math.floor(time / day);
      const h = Math.floor((time - d * day) / hours);
      const m = Math.floor((time - d * day - h * hours) / minutes);
      const s = Math.floor((time - d * day - h * hours - m * minutes) / 1000);
      this.setData({
        d,
        h,
        m,
        s
      })
    },

    //定時事件
    tick: function() {
      let {
        lastTime
      } = this.data;

      timer = setTimeout(() => {
        if (lastTime < interval) {
          clearTimeout(timer);
          this.setData({
              lastTime: 0,
              result: ''
            },
            () => {
              this.defaultFormat(lastTime)
              if (this.onEnd) {
                this.onEnd();
              }
            }
          );
        } else {
          lastTime -= interval;
          this.setData({
              lastTime,
              result: this.properties.format ? this.properties.format(lastTime) : ''
            },
            () => {
              this.defaultFormat(lastTime)
              this.tick();
            }
          );
        }
      }, interval);
    },

    //初始化時間
    initTime: function(properties) {
      let lastTime = 0;
      let targetTime = 0;
      try {
        if (Object.prototype.toString.call(properties.target) === '[object Date]') {
          targetTime = Number(properties.target).getTime();
        } else {
          targetTime = new Date(Number(properties.target)).getTime();
        }
      } catch (e) {
        throw new Error('invalid target properties', e);
      }

      lastTime = targetTime - new Date().getTime();
      return {
        lastTime: lastTime < 0 ? 0 : lastTime,
      };
    },
    //時間結束回調事件
    onEnd: function() {
      this.triggerEvent('onEnd');
    }
  }
defaultFormat :默認時間處理函數 tick:定時事件 initTime 初始化時間
onEnd:時間結束的回調
  • 倒計時組件countDown.js完整代碼
var timer = 0;
var interval = 1000;
Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    target: {
      type: String,
    },
    format: {
      type: Function,
      default: null
    }
  },

  lifetimes: {
    attached() {
      //組件建立時
      this.setData({
        lastTime: this.initTime(this.properties).lastTime,  //根據 target 初始化組件的lastTime屬性
      }, () => {
        //開啓定時器
        this.tick();
        //判斷是否有format屬性 若是設置按照自定義format處理頁面上顯示的時間 沒有設置按照默認的格式處理
        if (typeof this.properties.format === 'object') {
          this.defaultFormat(this.data.lastTime)
        }
      })
    },

    detached() {
      //組件銷燬時清除定時器 防止爆棧
      clearTimeout(timer);
    },
  },

  /**
   * 組件的初始數據
   */
  data: {
    d: 0, //天
    h: 0, //時
    m: 0, //分
    s: 0, //秒
    result: '',  //自定義格式返回頁面顯示結果
    lastTime:''  //倒計時的時間錯
  },

  /**
   * 組件的方法列表
   */
  methods: {
    //默認處理時間格式
    defaultFormat: function(time) {
      const day = 24 * 60 * 60 * 1000
      const hours = 60 * 60 * 1000;
      const minutes = 60 * 1000;

      const d = Math.floor(time / day);
      const h = Math.floor((time - d * day) / hours);
      const m = Math.floor((time - d * day - h * hours) / minutes);
      const s = Math.floor((time - d * day - h * hours - m * minutes) / 1000);
      this.setData({
        d,
        h,
        m,
        s
      })
    },

    //定時事件
    tick: function() {
      let {
        lastTime
      } = this.data;

      timer = setTimeout(() => {
        if (lastTime < interval) {
          clearTimeout(timer);
          this.setData({
              lastTime: 0,
              result: ''
            },
            () => {
              this.defaultFormat(lastTime)
              if (this.onEnd) {
                this.onEnd();
              }
            }
          );
        } else {
          lastTime -= interval;
          this.setData({
              lastTime,
              result: this.properties.format ? this.properties.format(lastTime) : ''
            },
            () => {
              this.defaultFormat(lastTime)
              this.tick();
            }
          );
        }
      }, interval);
    },

    //初始化時間
    initTime: function(properties) {
      let lastTime = 0;
      let targetTime = 0;
      try {
        if (Object.prototype.toString.call(properties.target) === '[object Date]') {
          targetTime = Number(properties.target).getTime();
        } else {
          targetTime = new Date(Number(properties.target)).getTime();
        }
      } catch (e) {
        throw new Error('invalid target properties', e);
      }

      lastTime = targetTime - new Date().getTime();
      return {
        lastTime: lastTime < 0 ? 0 : lastTime,
      };
    },
    //時間結束回調事件
    onEnd: function() {
      this.triggerEvent('onEnd');
    }
  }
})
  • 倒計時組件countDown.wxml完整代碼
<wxs src="../wxs/utils.wxs" module="utils" />
<wxs src="../../comm.wxs" module="comm" />
<view class="count-down">
  <text wx:if="{{result!==''}}">{{result}}</text>
  <block wx:else>
    <text wx:if="{{comm.numberToFixed(d)>0}}">{{d}}天</text>
    <text>{{utils.fixedZero(h)}}</text>
    <text style="font-weight: 500">:</text>
    <text>{{utils.fixedZero(m)}}</text>
    <text style="font-weight: 500">:</text>
    <text>{{utils.fixedZero(s)}}</text>
  </block>
</view>
其中引入了兩個wxs文件中的函數
WXS(WeiXin Script)是小程序的一套腳本語言,結合 WXML,能夠構建出頁面的結構。 官方文檔
function fixedZero(val) {
  return val * 1 < 10 ? '0' + val : val;
}
//保留 pos位小數
function numberToFixed(number, pos) {
  if (number === null || number === '' || number < 0) return ''
  return parseFloat(number).toFixed(pos)
}

組件使用

  • 引入方式
"usingComponents": {
    "countDown": "../../../components/countDown/countDown"
  },
  • 代碼演示
<countDown bind:onEnd="getPageList" format="{{formatTime}}" target="{{creatTargetTime}}" />
const formatChinaDate = mss => {
  let days = parseInt(mss / (1000 * 60 * 60 * 24));
  let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
  let seconds = parseInt((mss % (1000 * 60)) / 1000);
  return days + ' 天 ' + hours + ' 小時 ' + minutes + ' 分鐘 ' + seconds + ' 秒 ';
};
data:{
    formatTime:formatChinaDate,
    creatTargetTime:1556428889000, //時間戳
}

getPageList:function(){
    //倒計時結束啦
    console.log('倒計時結束啦')
}

API

參數 說明 類別 默認值
format 時間格式化顯示 Function(time) x天00:00:00
target 目標時間 Date
onEnd 倒計時結束回調 funtion

補充

相關文章
相關標籤/搜索