1.下载dayjs插件
import { ref, onUnmounted, computed } from 'vue'
import dayjs from 'dayjs'
export const userCountDown = () => {
let timer = null
let time = ref(0)
// 格式化时间
const formTime = computed(() => {
return dayjs.unix(time.value).format('mm分ss秒')
})
function state(currenTime) {
// 把传过来的数据给响应式数据
time.value = currenTime
// 格式化时间
timer = setInterval(() => {
time.value--
if (time.value === 0) {
clearInterval(timer)
// 其他业务逻辑
}
}, 1000)
}
// 如果存在,组件销毁调用清除定时器
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
return { formTime, state }
}