notice.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const NOTICE_INTERVAL = 10000
  2. export const state = () => {
  3. return {
  4. notices: [],
  5. timers: {}
  6. }
  7. }
  8. export const mutations = {
  9. ADD_NOTICE(state, notice) {
  10. state.notices.push(notice)
  11. },
  12. UPDATE_NOTICE(state, { index, notice }) {
  13. this._vm.$set(state.notices, index, notice)
  14. },
  15. DELETE_NOTICE(state, index) {
  16. this._vm.$delete(state.notices, index)
  17. },
  18. ADD_NOTICE_TIMER(state, { id, timerId }) {
  19. this._vm.$set(state.timers, id, { timerId })
  20. },
  21. DELETE_NOTICE_TIMER(state, id) {
  22. this._vm.$delete(state.timers, id)
  23. }
  24. }
  25. export const actions = {
  26. addNotice({ commit }, { notice }) {
  27. return new Promise((resolve) => {
  28. const id = `f${(+new Date()).toString(16)}`
  29. commit('ADD_NOTICE', { ...notice, id, isShowed: true })
  30. resolve(id)
  31. })
  32. },
  33. addNoticeTimer({ commit, dispatch }, { id, interval = NOTICE_INTERVAL }) {
  34. const timerId = setTimeout(() => {
  35. dispatch('deleteNotice', { id })
  36. }, interval)
  37. commit('ADD_NOTICE_TIMER', { id, timerId })
  38. },
  39. deleteNoticeTimer({ state, commit }, { id }) {
  40. if (state.timers[id]) {
  41. clearTimeout(state.timers[id].timerId)
  42. commit('DELETE_NOTICE_TIMER', id)
  43. }
  44. },
  45. addNoticeWithInterval({ dispatch }, { notice, interval }) {
  46. return new Promise(async (resolve) => {
  47. const id = await dispatch('addNotice', { notice })
  48. dispatch('addNoticeTimer', { id, interval })
  49. resolve(id)
  50. })
  51. },
  52. deleteNotice({ state, commit, dispatch }, { id }) {
  53. const index = state.notices.findIndex((i) => {
  54. return i.id === id
  55. })
  56. if (index !== -1) {
  57. commit('DELETE_NOTICE', index)
  58. dispatch('deleteNoticeTimer', { id })
  59. }
  60. },
  61. updateNotice({ state, commit, dispatch }, { id = `f${(+new Date()).toString(16)}`, notice, interval }) {
  62. const { notices } = state
  63. const index = notices.findIndex((i) => {
  64. return i.id === id
  65. })
  66. if (index !== -1) {
  67. commit('UPDATE_NOTICE', {
  68. index,
  69. notice: {
  70. ...notices[index],
  71. isShowed: true,
  72. ...notice
  73. }
  74. })
  75. } else {
  76. commit('ADD_NOTICE', { ...notice, id, isShowed: true })
  77. }
  78. if (interval) {
  79. dispatch('deleteNoticeTimer', { id })
  80. dispatch('addNoticeTimer', { id, interval })
  81. }
  82. },
  83. showNotice({ state, commit, dispatch }, { id, isShowed = true }) {
  84. dispatch('updateNotice', {
  85. id,
  86. notice: {
  87. isShowed
  88. }
  89. })
  90. }
  91. }