notificationMessage.ts 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. async markMessageAsRead() {
  43. if (this.readCardMap.length === 0) return
  44. console.log('置为已读')
  45. this.readCardMap = []
  46. localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))
  47. // await $api.setMessageRead({ id: this.readCardMap }).then((res) => {
  48. // if (res.code === 200) {
  49. // this.readCardMap = []
  50. // localStorage.setItem('readCardMap', JSON.stringify(this.readCardMap))
  51. // // 在将消息标记为已读后,再次检查是否有新消息
  52. // this.hasUnreadMessages()
  53. // }
  54. // })
  55. },
  56. clearData() {
  57. this.notificationMsgList = []
  58. this.readCardMap = []
  59. this.hasNewMsg = false
  60. localStorage.removeItem('hasNewMsg')
  61. localStorage.removeItem('notificationMsgList')
  62. localStorage.removeItem('readCardMap')
  63. }
  64. }
  65. })