vue 闹钟提醒 实现
实现 Vue 闹钟提醒功能
核心思路
通过 Vue 组件结合浏览器通知 API 实现闹钟功能,需监听时间变化并在设定时间触发提醒。
基础组件结构
使用 Vue 3 的 Composition API 编写核心逻辑:
<template>
<div>
<input type="time" v-model="alarmTime" />
<button @click="setAlarm">设置闹钟</button>
<button @click="clearAlarm">清除闹钟</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const alarmTime = ref('');
let alarmInterval = null;
</script>
时间检测逻辑
通过定时器每分钟检查当前时间是否匹配设定时间:
const checkAlarm = () => {
if (!alarmTime.value) return;
const now = new Date();
const [hours, minutes] = alarmTime.value.split(':');
const alarmDate = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes
);
if (now >= alarmDate && now - alarmDate < 60000) {
triggerNotification();
clearAlarm();
}
};
const setAlarm = () => {
if (alarmInterval) clearInterval(alarmInterval);
alarmInterval = setInterval(checkAlarm, 60000);
checkAlarm(); // 立即检查一次
};
浏览器通知实现
需先请求通知权限,然后触发提醒:
const requestPermission = () => {
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission !== 'granted') {
console.warn('通知权限未授予');
}
});
}
};
const triggerNotification = () => {
if (Notification.permission === 'granted') {
new Notification('闹钟提醒', {
body: '设定的时间到了!',
icon: '/alert-icon.png'
});
} else {
alert('闹钟时间到了!');
}
};
onMounted(requestPermission);
清除闹钟功能
停止定时器并重置状态:
const clearAlarm = () => {
if (alarmInterval) {
clearInterval(alarmInterval);
alarmInterval = null;
}
alarmTime.value = '';
};
onUnmounted(clearAlarm);
增强功能建议
- 多闹钟支持:改用数组存储多个闹钟时间
- 铃声定制:通过 Web Audio API 播放自定义音频
- 持久化存储:使用 localStorage 保存闹钟设置
- 响应式样式:添加闹钟激活状态的视觉反馈
注意事项
- 浏览器通知需要用户手动授权
- 页面关闭后定时器会停止,如需后台提醒需改用 Service Worker
- 移动端可能限制自动播放音频,需用户交互触发







