count-down.js 2.06 KB
/**
 * countDown.js.
 * @author hgwang
 * @date 2016-07-27
 */
'use strict';
import Vue from 'vue';

Vue.directive('countDown', {
    bind: function(el, binding) {
        // 结束时间
        let value = binding.value.endTime || 0;
        let callbackFn = binding.value.callback;

        // 如果不为0的话根据剩余的秒数计算时间
        let leftTime = parseInt(binding.value.leftTime, 10);
        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 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, 10);
            let m = parseInt((val - h * 3600) / 60, 10);
            let s = parseInt(val - h * 3600 - m * 60, 10);

            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);
    }
});