<template > <div v-if="show"> <div class="flex"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4 mr-1"> <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /> </svg> <span>倒计时:{{ `${d || 0}天${h || 0}小时${m || 0}分${s || 0}秒` }}</span> </div> </div> </template> <script> export default { props: { endTime: { type: String, default: '' }, }, data() { return { d: '', h: '', m: '', s: '', timer: null, show:false } }, mounted() { clearTimeout(this.timer); this.countTime(); }, beforeDestroy() { clearTimeout(this.timer); }, methods: { countTime: function () { //获取当前时间 let date = new Date() let now = date.getTime() //设置截止时间 let endDate = new Date(this.endTime); let end = endDate.getTime() //时间差 let leftTime = end - now; //定义变量 d,h,m,s保存倒计时的时间 if (leftTime >= 0) { this.d = Math.floor(leftTime / 1000 / 60 / 60 / 24)//天数我没用到,暂且写上 this.h = Math.floor((leftTime / 1000 / 60 / 60) % 24) this.m = Math.floor((leftTime / 1000 / 60) % 60) this.s = Math.floor((leftTime / 1000) % 60) //递归每秒调用countTime方法,显示动态时间效果 this.timer = setTimeout(this.countTime, 1000) this.show=true } }, }, } </script>
以上内容存保存到到项目下的组件目录components/DateDown.vue
在需要的地方调用即可
<YDateDown :endTime=”netpc.com.cn” />
开始用setInterval实现发现会提示无法在客户端执行该函数,网上找到用回调setTimeout方式可行。