Pinia 管理消息通知中心未读队列,核心是全局响应式状态维护与实时同步:定义含 messages state、addMessage/markAsRead/clearAll actions 和 unreadCount/unreadList getters 的 notification store;通过 pinia-plugin-persistedstate 持久化至 localStorage;组件中用 storeToRefs 保持响应式,配合服务端 API 和 WebSocket 实现双向同步。
用 Pinia 管理消息通知中心的未读消息队列,核心是把“未读消息列表”作为全局状态集中维护,并确保新增、标记已读、清空等操作能实时同步到所有相关组件(比如右上角小红点、通知弹窗、侧边栏入口)。它不是简单存个数组,而是要兼顾响应性、持久化和业务逻辑隔离。
在 src/stores/notification.js 中创建独立 store:
id、title、content、timestamp、isRead 字段;建议用 ref([]) 或直接返回数组,保持响应式addMessage(msg)(去重插入)、markAsRead(id)(单条标记)、markAllAsRead()(批量)、clearAll()
unreadCount(过滤 isRead: false 的数量)、unreadList(按时间倒序的未读列表)用户关闭页面再打开,未读消息不该消失。Pinia 插件 pinia-plugin-persistedstate 可自动同步到 localStorage:
npm install pinia-plugin-persistedstate
main.js 注册时启用:createPinia().use(persistedState)
persist: { key: 'notification-store', paths: ['messages'] }(注意:state 中实际字段名要匹配)组件里不要直接解构 store 属性(会失去响应式),推荐用 storeToRefs:
import { storeToRefs } from 'pinia'
const notificationStore = useNotificationStore(),再 const { unreadCount, unreadList } = storeToRefs(notificationStore)
notificationStore.markAsRead(id),不直接改 unreadList.value
前端未读状态需和服务端对齐。常见做法:
fetchUnreadMessages() action 内发起 API 请求并更新 state)addMessage() 并触发系统通知