Vue3 项目使用 Moment.js 实现 YYYY/MM/DD 格式有效期倒计时问题
Vue3 基于Moment.js实现有效期倒计时调整方案
原代码存在的问题
- 目标日期传参错误:
moment(30-9-2022)会先执行算术运算得到负数,无法解析为正确日期,需传入符合YYYY/MM/DD格式的字符串参数 - 模板语法错误:表达式括号未闭合,且直接对时间差毫秒值调用
moment()无法得到预期的倒计时格式 - 缺少实时更新逻辑:仅在组件首次渲染时计算一次时间差,不会自动刷新倒计时
调整后可运行代码
选项式API写法(适配原有代码风格)
<template> <p>Remaining time: {{ remainingTime }}</p> </template> <script> import moment from "moment"; export default { data() { return { // 按需求替换为你需要的YYYY/MM/DD格式目标日期 targetDate: '2022/09/30', remainingTime: '', timer: null } }, mounted() { // 组件挂载后立即计算一次 this.calculateRemaining() // 每秒刷新一次倒计时 this.timer = setInterval(() => { this.calculateRemaining() }, 1000) }, beforeUnmount() { // 组件卸载时清除定时器,避免内存泄漏 clearInterval(this.timer) }, methods: { calculateRemaining() { const now = moment() const end = moment(this.targetDate, 'YYYY/MM/DD') // 处理目标日期已过期的情况 if (end.isBefore(now)) { this.remainingTime = '已过期' clearInterval(this.timer) return } // 计算时间差拆分天、时、分、秒 const diff = end.diff(now) const days = Math.floor(diff / (1000 * 60 * 60 * 24)) const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)) const seconds = Math.floor((diff % (1000 * 60)) / 1000) // 可根据需求自定义显示格式 this.remainingTime = `${days}天 ${hours}时 ${minutes}分 ${seconds}秒` } } } </script>
组合式API(
相关产品推荐
相关产品推荐

