notificationMessage.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { defineStore } from 'pinia'
  2. interface NotificationMessageState {
  3. notificationMsgList: string[] // 页面中监听的未读消息id
  4. readCardMap: string[] // 已读的消息id
  5. hasNewMsg: boolean
  6. }
  7. export const useNotificationMessage = defineStore('notificationMessage', {
  8. state: (): NotificationMessageState => ({
  9. notificationMsgList: JSON.parse(localStorage.getItem('notificationMsgList')) || [],
  10. readCardMap: JSON.parse(localStorage.getItem('readCardMap')) || [],
  11. hasNewMsg: JSON.parse(localStorage.getItem('hasNewMsg')) || false
  12. }),
  13. getters: {},
  14. actions: {
  15. concatNotificationMsgList(array: any[]) {
  16. this.notificationMsgList = [...new Set([...this.notificationMsgList, ...array])]
  17. localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
  18. },
  19. removeNotificationMsgList(array: any[]) {
  20. this.notificationMsgList = this.notificationMsgList.filter((item) => !array.includes(item))
  21. localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
  22. },
  23. setReadCardMap(id: string) {
  24. // 将页面中从未读到已读的消息id存入readCardMap
  25. if (this.readCardMap.includes(id)) return
  26. this.readCardMap.push(id)
  27. localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))
  28. // 将已读的消息从notificationMsgList中删除
  29. this.notificationMsgList = this.notificationMsgList.filter((item) => {
  30. return !this.readCardMap.includes(item)
  31. })
  32. localStorage.setItem('notificationMsgList', JSON.stringify(this.notificationMsgList))
  33. },
  34. hasUnreadMessages() {
  35. $api.hasUnreadMessages().then((res) => {
  36. if (res.code === 200) {
  37. this.hasNewMsg = res.data.has_message
  38. localStorage.setItem('hasNewMsg', JSON.stringify(this.hasNewMsg))
  39. }
  40. })
  41. },
  42. setHasNewMsg() {
  43. this.hasNewMsg = true
  44. localStorage.setItem('hasNewMsg', JSON.stringify(this.hasNewMsg))
  45. },
  46. async markMessageAsRead() {
  47. if (this.readCardMap.length === 0) return
  48. await $api.setMessageRead({ id: this.readCardMap }).then((res) => {
  49. if (res.code === 200) {
  50. this.readCardMap = []
  51. localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))
  52. // 在将消息标记为已读后,再次检查是否有新消息
  53. this.hasUnreadMessages()
  54. }
  55. })
  56. },
  57. clearData() {
  58. this.notificationMsgList = []
  59. this.readCardMap = []
  60. this.hasNewMsg = false
  61. localStorage.removeItem('hasNewMsg')
  62. localStorage.removeItem('notificationMsgList')
  63. localStorage.removeItem('readCardMap')
  64. }
  65. }
  66. })