码迷,mamicode.com
首页 > 其他好文 > 详细

vue实现倒计时的插件 时间戳 刷新 跳转 都不影响

时间:2017-03-30 11:42:44      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:代码   int   end   计时   form   slot   floor   ndt   组件   

我发现好多倒计时的插件,刷新都会变成从头再来,于是自己用vue2.0写了一个,测试通过,直接上代码

如下是组件代码:

 <template>
    <span :endTime="endTime" :callback="callback" :endText="endText">
        <slot>
            {{content}}
        </slot>
    </span>
</template>
<script>
    export default {
        data(){
           return {
            content: ‘‘,
           }
        },
        props:{
            endTime:{
                type: String,
                default :‘‘
            },
            endText:{
               type : String,
               default:‘已结束‘
            },
            callback : {
                type : Function,
                default :‘‘
            }
        },
        mounted () {
          this.countdowm(this.endTime)
        },
        methods: {
           countdowm(timestamp){
            let self = this;
            let timer = setInterval(function(){
                let nowTime = new Date();
                let endTime = new Date(timestamp * 1000);
                let t = endTime.getTime() - nowTime.getTime();
                if(t>0){
                    let day = Math.floor(t/86400000);
                    let hour=Math.floor((t/3600000)%24);
                    let min=Math.floor((t/60000)%60);
                    let sec=Math.floor((t/1000)%60);
                    hour = hour < 10 ? "0" + hour : hour;
                    min = min < 10 ? "0" + min : min;
                    sec = sec < 10 ? "0" + sec : sec;
                    let format = ‘‘;
                    if(day > 0){
                       format =  `${day}天${hour}小时${min}分${sec}秒`;
                    }
                    if(day <= 0 && hour > 0 ){
                       format = `${hour}小时${min}分${sec}秒`;
                    }
                    if(day <= 0 && hour <= 0){
                       format =`${min}分${sec}秒`;
                    }
                    self.content = format;
                    }else{
                      clearInterval(timer);
                      self.content = self.endText;
                      self._callback();
                    }
                 },1000);
               },
               _callback(){
               if(this.callback && this.callback instanceof Function){
                     this.callback(...this);
                 }
            }
        }
    }
</script>

下面是调用代码:

<count-down endTime="1490761620" :callback="callback" endText="已经结束了"></count-down>

ednTime 是时间结束之后的时间戳  callback是结束之后的回调  endText是结束之后的文字显示!

vue实现倒计时的插件 时间戳 刷新 跳转 都不影响

标签:代码   int   end   计时   form   slot   floor   ndt   组件   

原文地址:http://www.cnblogs.com/sichaoyun/p/6645042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!