vue实现每日到点提醒
实现每日到点提醒的Vue方案
使用浏览器通知API
通过Notification API实现桌面通知功能,需先获取用户授权。在Vue组件中可封装如下逻辑:
export default {
methods: {
requestNotificationPermission() {
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
this.scheduleDailyReminder();
}
});
}
},
scheduleDailyReminder() {
const targetHour = 9; // 设置提醒时间(24小时制)
const now = new Date();
const targetTime = new Date();
targetTime.setHours(targetHour, 0, 0, 0);
if (now > targetTime) {
targetTime.setDate(targetTime.getDate() + 1);
}
const timeout = targetTime - now;
setTimeout(() => {
new Notification('每日提醒', {
body: '这是您的预定提醒内容',
icon: '/notification-icon.png'
});
this.scheduleDailyReminder(); // 递归调用实现每日重复
}, timeout);
}
},
mounted() {
this.requestNotificationPermission();
}
}
结合本地存储记录状态
防止页面刷新后定时器失效,可使用localStorage保存状态:

// 在scheduleDailyReminder方法中添加
localStorage.setItem('nextReminderTime', targetTime.getTime());
// 组件初始化时检查已有定时
const storedTime = localStorage.getItem('nextReminderTime');
if (storedTime && new Date(parseInt(storedTime)) > new Date()) {
const remainingTime = parseInt(storedTime) - Date.now();
setTimeout(() => {
this.triggerNotification();
this.scheduleDailyReminder();
}, remainingTime);
}
使用Web Worker保持后台运行
解决浏览器标签页休眠导致定时器不准确的问题:

// worker.js
self.onmessage = function(e) {
if (e.data === 'start') {
const targetHour = 9;
setInterval(() => {
const now = new Date();
if (now.getHours() === targetHour && now.getMinutes() === 0) {
self.postMessage('remind');
}
}, 60000); // 每分钟检查一次
}
};
// Vue组件中
const worker = new Worker('worker.js');
worker.onmessage = (e) => {
if (e.data === 'remind' && Notification.permission === 'granted') {
new Notification('定时提醒触发');
}
};
worker.postMessage('start');
完整组件示例
整合上述功能的单文件组件:
<template>
<div>
<button @click="requestPermission">启用每日提醒</button>
<p>当前提醒时间:每天{{ reminderTime }}点</p>
</div>
</template>
<script>
export default {
data() {
return {
reminderTime: 9
}
},
methods: {
requestPermission() {
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
this.initReminderSystem();
}
});
} else {
alert('该浏览器不支持通知功能');
}
},
initReminderSystem() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(() => {
this.scheduleViaServiceWorker();
});
} else {
this.scheduleViaTimeout();
}
},
scheduleViaTimeout() {
// ...前述setTimeout实现
},
scheduleViaServiceWorker() {
// 更可靠的后台提醒方案
}
}
}
</script>
注意事项
- 通知API需要HTTPS环境或localhost才能正常工作
- 移动端浏览器对后台运行的限制较多,建议配合Service Worker实现
- 首次使用需要用户主动授权,建议在合适的用户交互场景触发权限请求
- 考虑添加关闭提醒的功能开关,提升用户体验
扩展方案
对于更复杂的提醒需求,可考虑:
- 集成IndexedDB存储提醒配置
- 使用第三方推送服务如Firebase Cloud Messaging
- 开发浏览器扩展程序获得更稳定的后台权限






