Appearance
实现 生日倒计时 工具
分类:developer | 标签:生日、倒计时、年龄 算年龄与下次生日倒计时
2.1 功能说明
算年龄与下次生日倒计时
2.1.1 使用指南
功能说明
输入生日,计算精确到天的年龄,以及距离下一次生日的倒计时天数。
使用场景
纪念日提醒、年龄核对。
2.2 代码实现
2.2.1 组件结构
本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-input、el-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。
2.2.2 核心逻辑概览
<script setup> 中定义的主要函数/方法:
run()clear()
2.2.3 关键实现代码
以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。
vue
import { ref } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'
const date = ref('')
const error = ref('')
const result = ref(null)
function run() {
error.value = result.value = null
if (!date.value) { error.value = '请选择生日'; return }
const b = new Date(date.value)
if (isNaN(b)) { error.value = '日期无效'; return }
const now = new Date()
let age = now.getFullYear() - b.getFullYear()
const had = now.getMonth() > b.getMonth() || (now.getMonth() === b.getMonth() && now.getDate() >= b.getDate())
if (!had) age--
let next = new Date(now.getFullYear(), b.getMonth(), b.getDate())
if (next < new Date(now.getFullYear(), now.getMonth(), now.getDate())) next = new Date(now.getFullYear() + 1, b.getMonth(), b.getDate())
const days = Math.round((next - new Date(now.getFullYear(), now.getMonth(), now.getDate())) / 86400000)
result.value = { birth: date.value, age, next: next.toISOString().slice(0, 10), days }
}
function clear() { date.value = error.value = result.value = '' }2.3 效果截图
