vue实现番茄钟
使用 Vue 实现番茄钟
番茄钟是一种时间管理方法,通常将工作时间划分为25分钟的专注时段(称为“番茄时间”)和5分钟的休息时段。以下是一个基于 Vue 3 的番茄钟实现方案。
核心功能实现
安装 Vue 3 确保已安装 Vue 3 环境。若未安装,可通过以下命令初始化项目:
npm init vue@latest pomodoro-timer
cd pomodoro-timer
npm install
定义状态和数据 在 Vue 组件中定义番茄钟的核心状态:
const workDuration = 25 * 60; // 25分钟(以秒为单位)
const breakDuration = 5 * 60; // 5分钟(以秒为单位)
const state = reactive({
timeLeft: workDuration,
isRunning: false,
isWorkTime: true,
timer: null
});
计时器逻辑 实现开始、暂停和重置功能:

function startTimer() {
if (state.isRunning) return;
state.isRunning = true;
state.timer = setInterval(() => {
state.timeLeft--;
if (state.timeLeft <= 0) {
clearInterval(state.timer);
switchMode();
}
}, 1000);
}
function pauseTimer() {
clearInterval(state.timer);
state.isRunning = false;
}
function resetTimer() {
pauseTimer();
state.timeLeft = state.isWorkTime ? workDuration : breakDuration;
}
function switchMode() {
state.isWorkTime = !state.isWorkTime;
state.timeLeft = state.isWorkTime ? workDuration : breakDuration;
startTimer();
}
界面设计
模板部分 使用 Vue 模板绑定状态和事件:
<template>
<div class="pomodoro">
<h2>{{ state.isWorkTime ? 'Work Time' : 'Break Time' }}</h2>
<div class="time-display">
{{ formatTime(state.timeLeft) }}
</div>
<div class="controls">
<button @click="startTimer" :disabled="state.isRunning">Start</button>
<button @click="pauseTimer" :disabled="!state.isRunning">Pause</button>
<button @click="resetTimer">Reset</button>
</div>
</div>
</template>
时间格式化
将秒数转换为 MM:SS 格式:

function formatTime(seconds) {
const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
const secs = (seconds % 60).toString().padStart(2, '0');
return `${mins}:${secs}`;
}
样式优化
添加基础样式以提升用户体验:
.pomodoro {
text-align: center;
font-family: Arial, sans-serif;
}
.time-display {
font-size: 3rem;
margin: 20px 0;
}
.controls button {
margin: 0 5px;
padding: 8px 16px;
font-size: 1rem;
}
扩展功能
音效提醒 在模式切换时播放提示音:
function playSound() {
const audio = new Audio('path/to/notification.mp3');
audio.play();
}
function switchMode() {
playSound();
state.isWorkTime = !state.isWorkTime;
state.timeLeft = state.isWorkTime ? workDuration : breakDuration;
}
任务统计 记录完成的番茄钟数量:
const stats = reactive({
workSessions: 0
});
function switchMode() {
if (!state.isWorkTime) stats.workSessions++;
// 其余逻辑不变
}
通过以上步骤,可以构建一个功能完整的 Vue 番茄钟应用。用户可根据需求进一步扩展,如添加自定义时间设置、历史记录等功能。






