ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

vue3 之 倒计时函数封装

vue3 之 倒计时函数封装

理解需求

编写一个函数useCountDown可以把秒数格式化为倒计时的显示xx分钟xx秒
1️⃣formatTime为显示的倒计时时间
2️⃣start是倒计时启动函数,调用时可以设置初始值并且开始倒计时

实现思路分析

在这里插入图片描述

安装插件 dayjs

npm i dayjs

倒计时逻辑函数封装

// 封装倒计时逻辑函数
import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'
export const useCountDown = () => {// 1. 响应式的数据let timer = nullconst time = ref(0)// 格式化时间 为 xx分xx秒const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))// 2. 开启倒计时的函数const start = (currentTime) => {// 开始倒计时的逻辑// 核心逻辑的编写:每隔1s就减一time.value = currentTimetimer = setInterval(() => {time.value--}, 1000)}// 组件销毁时清除定时器onUnmounted(() => {timer && clearInterval(timer)})return {formatTime,start}
}

页面使用

import { useCountDown } from '@/composables/useCountDown'
const { formatTime, start } = useCountDown()
// 获取数据
const payInfo = ref({})
const getPayInfo = async () => {const res = await getOrderAPI(route.query.id)payInfo.value = res.result// 初始化倒计时秒数start(res.result.countdown)
}
onMounted(() => getPayInfo())<template><div class="tip"><p>订单提交成功!请尽快完成支付。</p><p>支付还剩 <span>{{ formatTime }}</span>, 超时后将取消订单</p></div>
</template> 

dayjs官网

返回列表