index.js 2.23 KB
let timer;
Component({
    properties: {
        type: String,
        current: {
            type: Number,
            observer: '_dataChange'
        },
        begin: Number,
        end: Number
    },
    data: {
        label: '',
        days: '',
        hours: '',
        minutes: '',
        seconds: '',
        diff: '',
        fullContent: ''
    },
    pageLifetimes: {
        show() {
            console.log('show');
        },
        hide() {
            console.log('hide');
            clearInterval(timer);
        }
    },
    methods: {
      _dataChange() {
          const {current, begin, end} = this.data;

          let label = '距开售';

          // if (current && begin && end) {
          //     label = begin - current > 0 ? '距离活动开始' : '距离活动结束';
          // }

          this.data.diff = Math.abs(begin - current > 0 ? begin - current : end - current);
          if (timer) {
              clearInterval(timer);
          }
          this.tick(label);

          timer = setInterval(() => {
              this.tick(label);
              --this.data.diff;
              if (this.data.diff < 0) {
                  clearInterval(timer);
                  this.triggerEvent('endcountdown', {
                      isEnd: current - begin > 0
                  });
              }
          }, 1000);
      },
      tick(label) {
          let diff = this.data.diff;
          let days = Math.floor(diff / (24 * 3600));

          days = days > 9 ? days : '0' + days;

          let leave1 = diff % (24 * 3600);
          let hours = Math.floor(leave1 / (3600));

          hours = hours > 9 ? hours : '0' + hours;

          let leave2 = leave1 % 3600;
          let minutes = Math.floor(leave2 / 60);

          minutes = minutes > 9 ? minutes : '0' + minutes;

          let seconds = leave2 % 60;

          seconds = seconds > 9 ? seconds : '0' + seconds;

          // let fullContent = label + ' ' + days + ' 天 ' + hours + ':' + minutes + ':' + seconds;
          let fullContent = days + ' :' + hours + ' :' + minutes;

          this.setData({
              label,
              days,
              hours,
              minutes,
              seconds,
              fullContent
          });
      }
  }
});