/
index.js
93 lines (74 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import Toast from './Toast.vue'
function init(Vue, globalOptions = {}) {
let cmp = null
const queue = []
const property = globalOptions.property || '$toast'
function createCmp(options) {
const component = new Vue(Toast)
const componentOptions = { ...Vue.prototype[property].globalOptions, ...options }
if (componentOptions.slot) {
component.$slots.default = componentOptions.slot
delete componentOptions.slot
}
Object.assign(component, componentOptions)
document.body.appendChild(component.$mount().$el)
return component
}
function show(message, options = {}) {
if (cmp) {
const isQueueable = options.queueable !== undefined ? options.queueable : globalOptions.queueable
if (isQueueable) {
queue.push({ message, options })
}
else {
cmp.close()
queue.unshift({ message, options })
}
return
}
options.message = message
cmp = createCmp(options)
cmp.$on('statusChange', (isActive, wasActive) => {
if (wasActive && !isActive) {
cmp.$nextTick(() => {
cmp.$destroy()
cmp = null
if (queue.length) {
const toast = queue.shift()
show(toast.message, toast.options)
}
})
}
})
}
function shorts(options) {
const colors = ['success', 'info', 'error', 'warning']
const methods = {}
colors.forEach(color => {
methods[color] = (message, options) => show(message, { color, ...options })
})
if (options.shorts) {
for (let key in options.shorts) {
const localOptions = options.shorts[key]
methods[key] = (message, options) => show(message, { ...localOptions, ...options })
}
}
return methods
}
function getCmp() {
return cmp
}
function clearQueue() {
return queue.splice(0, queue.length)
}
Vue.prototype[property] = Object.assign(show, {
globalOptions,
getCmp,
clearQueue,
...shorts(globalOptions)
})
}
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(init)
}
export default init