vue3倒计时组件

844 阅读1分钟

vue3倒计时组件

最近闲来无事,就想着把工作中遇到的一个倒计时的功能写写,封装了一下组件

1、计算倒计时

首先
  • 首先计算后端接口给的日期和当前日期的差值(这里我们利用时间戳相减)
  • 在unites工具文件夹下面创建一个Timers.js
// 倒计时  getTime1:数据日期 getTime2当前日期
export const countdown = (end, begin = getdateTime()) => {
    var beginDate = new Date(begin);
    var endDate = new Date(end);
    var diff = endDate.getTime() - beginDate.getTime();
    
    //这里计算如果是负数的处理
    var sec = diff < 0 ? (Math.abs(diff / 1000)) * -1 : diff / 1000;
    return formateTime(sec);
}
  • 在Timers.js文件中继续定义一个日期格式化的函数
function formateTime(times) {
    let time = Math.abs(times)
    const h = parseInt(time / 3600)
    const minute = parseInt(time / 60 % 60)
    const second = Math.ceil(time % 60)
    const hours = h < 10 ? '0' + h : h
    const formatSecond = second > 59 ? 59 : second
    return `${times < 0 ? '超时' : ''}${hours > 0 ? `${hours}:` : '00:'}${minute < 10 ? '0' + minute : minute}:${formatSecond < 10 ? '0' + formatSecond : formatSecond}`
}

2、创建countdown组件

<template>
    <div :style="{ 'color': times.includes('超时') ? 'red' : '' }">
        {{ times }}
    </div>
</template><script setup>
import { ref, onMounted, onBeforeUnmount } from "vue"
import { countdown } from '@/units/Timers.js'
const props = defineProps({
    timeLimitBy: String,
})
const times = ref('')
​
onMounted(() => {
    setInterval(upotimes, 1000);
})
​
// 不断的变时间
const upotimes = () => {
    times.value = countdown(props.timeLimitBy, new Date())
}
onBeforeUnmount(() => {
    clearInterval()
})
</script><style lang="scss" scoped></style>

3、其他组件上面引入调用就行了

  • 在App.vue
             <vxe-column min-width="20" title="倒计时" cell-type="string" show-overflow>
                    <template #default="{ row }">
                          <!-- row 是列表的值 -->
                        <div >
                            <countdown :timeLimitBy="row.timeLimitByQS" />
                        </div>
                    </template>
                </vxe-column>