1.js封装部分
// 封装倒计时逻辑函数
import {computed, onUnmounted, ref} from 'vue';
// 这里要使用npm install dayjs安装也可以查看官网安装
import dayjs from 'dayjs';
export const useCountDown = ()=> {
let timeout = null;
// 1.响应式数据
const time = ref(0);
// 2.start方法接收传入的时间参数为incomingTime
const start = (incomingTime)=>{
time.value = incomingTime;
timeout = setInterval(() => {
time--;
}, 1000);
}
// 3.格式化时间 为 xx分xx秒
const formatTime = computed(()=>{dayjs.unix(time.value).format('mm分ss秒')});
// 4.组件销毁清除定时器防止内存溢出
onUnmounted(()=>{
timeout && clearInterval(timeout);
})
return {
start,
formatTime
}
}
2.调用方法和使用页面相关代码
<template>
<div>
<div class="tip">
<p>订单提交成功! 请尽快完成支付。</p>
<p>支付还剩<span>{{ formatTime }}</span>, 超时后将取消订单</p>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { getOrdeAPI } from '@/api/order';
import { useCountDown } from '@/composables/useCountDown';
// 解构赋值
const {start, formatTime} = useCountDown();
// 获取路由参数调用useRoute=>const route = useRoute();、使用路由跳转useRouter=>const router = useRouter();
const route = useRoute();
// 获取订单数据
const payInfo = ref({});
const getPayInfo = async ()=>{
const res = await getOrdeAPI(route.query.id);
payInfo.value = res.result;
// 初始化倒计时秒数
start(res.result.countdown);
}
onMounted(() => {getPayInfo()})
</script>
<style scoped lang='less'>
</style>
3.效果如图: