|
| 1 | +import { GetterTree, Store, MutationTree } from 'vuex' |
| 2 | + |
| 3 | +export const state = () => ({ |
| 4 | + show: false, |
| 5 | + content: '', |
| 6 | + theme: 'info', |
| 7 | + iconHTML: '', |
| 8 | + autoDismiss: true, |
| 9 | + timeout: 5000, |
| 10 | +}) |
| 11 | +let timeoutId: NodeJS.Timeout |
| 12 | + |
| 13 | +export type ToastState = ReturnType<typeof state> |
| 14 | + |
| 15 | +export const getters: GetterTree<ToastState, ToastState> = { |
| 16 | + show: (state) => state.show, |
| 17 | + content: (state) => state.content, |
| 18 | + theme: (state) => state.theme, |
| 19 | + iconHTML: (state) => state.iconHTML, |
| 20 | + autoDismiss: (state) => state.autoDismiss, |
| 21 | + timeout: (state) => state.timeout, |
| 22 | +} |
| 23 | + |
| 24 | +export const mutations: MutationTree<ToastState> = { |
| 25 | + show(state, { show, content, iconHTML, theme }: ToastState) { |
| 26 | + if (!show) { |
| 27 | + state.show = show |
| 28 | + return |
| 29 | + } |
| 30 | + const isAlreadyShowing = state.show |
| 31 | + state.content = content |
| 32 | + state.theme = theme || 'info' |
| 33 | + state.iconHTML = iconHTML |
| 34 | + state.show = !!content && show |
| 35 | + if (isAlreadyShowing && state.show && timeoutId) { |
| 36 | + clearTimeout(timeoutId) |
| 37 | + } |
| 38 | + if (state.show) { |
| 39 | + timeoutId = setTimeout(() => { |
| 40 | + const store = this as unknown as Store<ToastState> |
| 41 | + store.commit('toast/show', { show: false }) |
| 42 | + }, 5000) |
| 43 | + } |
| 44 | + }, |
| 45 | +} |
0 commit comments