zoukankan      html  css  js  c++  java
  • Vue 倒计时组件封装

    项目中需要用到倒计时的功能,封装了一个组件。
    代码解读:

    • 1:created周期中获取传入参数时间的剩余秒数: this.initSecondsLeft() 并绑定间隔事件 intervalEvent
    • 2: 在computed属性中刷新当前剩余时间的结果
    • 3: 结束后触发父组件的handle-done事件,父组件做出对应操作,如弹窗或信息提示
    <template>
      <div>
        <div style="text-align:center;color:red;">
          <h2>{{showTimeLeft}}</h2>
        </div>
        <div style="text-align:center;color:green;">
          <h2>{{showTimeLeft}}</h2>
        </div>
      </div>
    </template>
    <script>
    export default {
      name: "timeCountDown",
      props: {
        endDate: String,
      },
      data() {
        return {
          timeLeft: 0,
          bundleIntervalEvent: ""
        };
      },
      computed: {
        //用计算属性显示结果
        showTimeLeft() {
          //剩余秒数<=0
          if (this.timeLeft <= 0) {
            // 结束event
            this.$emit('handle-done', true)
            return "已过期";
          }
          // 剩余秒数>0
          else {
            let day = Math.floor(this.timeLeft / 86400);
            let hour = Math.floor((this.timeLeft % 86400) / 3600);
            let min = Math.floor(((this.timeLeft % 86400) % 3600) / 60);
            let sec = Math.floor(((this.timeLeft % 86400) % 3600) % 60);
            return (day + "天  " + (hour < 10 ? "0" : "") + hour + ": " + (min < 10 ? "0" : "") + min + ": " + (sec < 10 ? "0" : "") + sec
            );
          }
        }
      },
      methods: {
        //和当前日期比较,计算剩余多少秒
        initSecondsLeft() {
          let currentDate = new Date();
          let tmp = this.endDate.split(/[- : /]/);
          let toEndDate = new Date(tmp[0], tmp[1] - 1, tmp[2], tmp[3], tmp[4], tmp[5]);
          //参数日期 > 当前日期 => 获取剩余秒数
          if (toEndDate > currentDate) {
            this.timeLeft = Math.floor((toEndDate.getTime() - currentDate.getTime()) / 1000);
          } else {
            this.timeLeft = 0;
          }
        },
        //间隔事件: 剩余秒数--, 当剩余秒数为0时,清除间隔事件.
        intervalEvent() {
          if (this.timeLeft > 0) {
            this.timeLeft--;
          } else {
            clearInterval(this.bundleIntervalEvent);
          }
        },
      },
      mounted() {
      },
      created() {
        //初始化剩余秒数
        this.initSecondsLeft();
        //执行间隔事件.
        this.bundleIntervalEvent = setInterval(this.intervalEvent, 1000);
      },
      beforeDestroy() {
        clearInterval(this.bundleIntervalEvent);
      }
    };
    </script>
    
    Keep learning
  • 相关阅读:
    【cocos2d-js网络教程篇】cocos2d-js http网络请求
    COCOS2D
    Laravel5中的Session
    Laravel 下配置 Redis 让缓存、Session 各自使用不同的 Redis 数据库
    cocos-js Http方式网络请求
    Python语法31[module/package+import]
    cocos2d-js callFunc传参
    安装pygame for Python3.5
    阿里云vsftp安装和简单的配置
    Git代码行统计命令集
  • 原文地址:https://www.cnblogs.com/leslie1943/p/13364574.html
Copyright © 2011-2022 走看看