count-down.js 2.13 KB
/**
 * countDown.js.
 * @author hgwang
 * @date 2016-07-27
 */
'use strict';
let Vue = require('vue');

Vue.directive('countDown', {
    acceptStatement: true,
    params: ['left-time', 'callback', 'end-time'],
    update: function() {
        // 结束时间
        let value = this.params.endTime || 0;
        let callbackFn = this.params.callback;

        // 如果不为0的话根据剩余的秒数计算时间
        let leftTime = parseInt(this.params.leftTime);
        let newValue;

        if (leftTime !== 0) {
            newValue = new Date() - 0 + leftTime * 1000;
        } else {
            if (value) {
                newValue = value.replace(/-/g, '/').substring(0, 19);
            } else {
                return '';
            }
        }

        if (new Date(newValue) === 'Invalid Date') {
            return console.error('The param of directive "v-time-down" must be a date string!');
        }
        let timerSS = null;
        let el = this.el;
        let hDom = document.createElement('span');

        hDom.setAttribute('class', 'timeDown-H');

        el.appendChild(hDom);

        let last = 0;

        function format(val) {
            let result = '00:00:00';

            if (val === 0) {
                return result;
            }
            let h = parseInt(val / 3600);
            let m = parseInt((val - h * 3600) / 60);
            let s = parseInt(val - h * 3600 - m * 60);

            h = h < 10 ? '0' + h : h;
            m = m < 10 ? '0' + m : m;
            s = s < 10 ? '0' + s : s;
            if (h === 0) {
                result = m + ':' + s;
            } else {
                result = h + ':' + m + ':' + s;
            }
            return result;
        }

        function countdown() {
            last = (new Date(newValue)).getTime() - (new Date()).getTime();
            last = last / 1000;
            if (last <= 0) {
                clearInterval(timerSS);
                last = 0;
                callbackFn && callbackFn();
            }
            el.querySelector('.timeDown-H').innerHTML = format(last);
        }

        countdown();
        timerSS = setInterval(countdown, 1000);
    }
});