直接上代码,复制可用。

1、html部分

<p style="line-height: 1.5rem;" v-html="countTxt"></p>

2、script部分

import { formateTimeStamp } from '@/util/tools.js'
export default {
  props: {
    infos: { type: [Array, Object] }
  },
  data () {
    return {
      times: {},
      countTxt: ''
    }
  },
  methods: {
    // 获得距离活动开始还剩余的时间
    mistiming () {
      var timeStamp = this.infos.activity.end_at - this.infos.activity.start_at;
      this.times = formateTimeStamp(timeStamp);
      const str = `<span>${this.times.day}</span>天<span>${this.times.hour}</span>时<span>${this.times.min}</span>分<span>${this.times.seconds}</span>秒`
      this.countTxt = str;
      var TimeDown = setInterval(() => {
        if (timeStamp > 0) {
          timeStamp--;
          const newTime = formateTimeStamp(timeStamp);
          const str = `<span>${newTime.day}</span>天<span>${newTime.hour}</span>时<span>${newTime.min}</span>分<span>${newTime.seconds}</span>秒`
          this.countTxt = str;
        } else {
          this.countTxt = '活动已开始'
          clearInterval(TimeDown);
        }
      }, 1000)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.mistiming();
    })
  }
}

3、tools.js

// 计算出时间戳的具体数据:比如将85400转化为 n天n时n分n秒
export function formateTimeStamp (timeStamp) {
  var day;
  var hour;
  var min;
  var seconds;

  day = parseInt(timeStamp / (24 * 60 * 60)) // 计算整数天数
  var afterDay = timeStamp - day * 24 * 60 * 60 // 取得算出天数后剩余的秒数
  hour = parseInt(afterDay / (60 * 60)) // 计算整数小时数
  var afterHour = timeStamp - day * 24 * 60 * 60 - hour * 60 * 60 // 取得算出小时数后剩余的秒数
  min = parseInt(afterHour / 60) // 计算整数分
  seconds = parseInt(timeStamp - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60) // 取得算出分后剩余的秒数

  if (day < 10) {
    day = '0' + day;
  }

  if (hour < 10) {
    hour = '0' + hour
  };

  if (min < 10) {
    min = '0' + min;
  }

  if (seconds < 10) {
    seconds = '0' + seconds;
  }

  const restStamp = {
    day: day,
    hour: hour,
    min: min,
    seconds: seconds
  }
  return restStamp
}

效果:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐