如何使用Vue.js实现按当月天数自动循环的倒计时计时器
实现每月自动循环倒计时的调整方案
核心逻辑为自动计算当月截止时间,倒计时结束后自动刷新为下一月的截止时间,即可实现按月循环的效果,具体调整步骤如下:
- 新增计算当月截止时间的工具函数,自动适配当月实际天数
// 函数返回当月最后一天23:59:59的时间戳 function getMonthEndTime() { const now = new Date() // 利用Date特性:传入月份+1、日期为0时,自动返回当月最后一天 const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59) return currentMonthEnd.getTime() }
- 调整原有组件逻辑,绑定倒计时结束回调实现自动循环
<template> <div> <!-- 新增finish事件绑定,倒计时结束触发回调 --> <countdown :endtime="endtime" @finish="resetCountdown" /> </div> </template> <script> export default { data() { return { // 初始化时直接取当月截止时间 endtime: this.getMonthEndTime() } }, methods: { getMonthEndTime() { const now = new Date() const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59) return currentMonthEnd.getTime() }, resetCountdown() { // 倒计时结束后自动更新为下一月的截止时间 this.endtime = this.getMonthEndTime() } } } </script>
- 自定义截止日期调整说明
如果需要将每月截止时间设置为固定日期(比如每月10号),只需修改getMonthEndTime逻辑即可,示例如下:
// 调整为每月10号23:59:59作为截止时间 getMonthEndTime() { const now = new Date() let targetMonth = now.getMonth() // 如果当前日期已经超过当月10号,自动取下个月10号 if (now.getDate() > 10) { targetMonth += 1 } return new Date(now.getFullYear(), targetMonth, 10, 23, 59, 59).getTime() }
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

