moment.js 制作一个倒计时

您所在的位置:网站首页 vue实现倒计时五分钟 moment.js 制作一个倒计时

moment.js 制作一个倒计时

2023-07-14 06:51| 来源: 网络整理| 查看: 265

后端返回一个活动到期时间戳(s),前端需要根据这个时间做个倒计时,倒计时的精度为:xx天xx小时xx分钟xx秒

一个常见的活动倒计时。

注意:秒要转为ms毫秒,moment计算是以毫秒为单位的。

那么moment.js怎么计算出这些值呢?

纯文本显示倒计时

这个就要看你的样式了,如果你的要求只是显示纯文字:xx天xx小时xx分钟xx秒那么可以直接使用format方法。

import moment from "moment"; moment.locale("zh-cn"); //汉化 export default { data(){ return { endTime:1614217890000, //ms 到期时间 time:"",//倒计时内容 } }, methods(){ countdown(){ const diffTime = this.endTime - moment(); return moment(diffTime).format("DD天HH小时mm分钟"); } } }

countdown方法计算到期时间与现在时间的时间差,然后通过format转换格式,转换为纯文本。

配合定时器这样写:

{{time}} import moment from "moment"; moment.locale("zh-cn"); //汉化 export default { data(){ return { endTime:1614217890000, //ms 到期时间 time:"",//倒计时内容 } }, methods(){ countdown(){ return moment(this.endTime - Date.now()).format("DD天HH小时mm分钟"); }, initCountdown(){ if(this.$countdown) clearInterval(this.$countdown); if(this.endTime - Date.now() > 0) { this.time = this.countdown(); //首次 //定时器 this.$countdown = setInterval(()=>{ if(this.endTime - Date.now() { if (key === "days") { const days = moment(this.endTime).diff(moment(), "days"); this.time[key] = this.prefixInteger(days, 2); } else { const diffTime = moment(this.endTime).diff(moment()); const timeVal = moment.duration(diffTime)[key](); this.time[key] = this.prefixInteger(timeVal, 2); } }); }, //初始化倒计时 initCountdown(){ if(this.$countdown) clearInterval(this.$countdown); if(this.endTime - Date.now() > 0) { this.time = this.countdown(); //首次 //定时器 this.$countdown = setInterval(()=>{ if(this.endTime - Date.now()


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3