1、首先安装环境
npm install dayjs -s
npm i @vueuse/core -s
2、新建一个conform.js其内容如下:
import {onUnmounted, ref} from "vue";
import {useIntervalFn} from "@vueuse/core";
import dayjs from "dayjs";
export const usePayTime = () => {
const time = ref(0)
const timeText = ref('')
const { pause, resume } = useIntervalFn(() => {
time.value--
console.log('time.value', time.value)
timeText.value = dayjs.unix(time.value).format('mm分ss秒')
if (time.value <= 0) {
pause()
}
}, 1000, false)
onUnmounted(() => {
pause()
})
const start = (countdown) => {
time.value = countdown
timeText.value = dayjs.unix(time.value).format('mm分ss秒')
resume()
}
return {
start,
timeText
}
}
3、在APP.vue 中使用,其内容如下:
<template>
<button @click="validate_ref">开始倒计时</button>
<div>
{{timeText}}
</div>
</template>
<script setup>
import { ref} from "vue";
import {usePayTime} from './conform'
const total_seconds = ref(60*2)
const { start, timeText } = usePayTime()
const minus = 60
const hours = minus*60
const days = hours*24
const noday = ref(172800)
const day = parseInt(noday.value/days)
const hour = parseInt((noday.value%days)/hours)
const min = parseInt((noday.value%hours)/minus)
const second = parseInt(noday.value%minus)
console.log('day', day)
console.log('hour', hour)
console.log('min', min)
console.log('second', second)
const validate_ref = ()=>{
start(total_seconds.value)
}
</script>
<style scoped lang="less">
</style>
4、效果如下:
