1 | import Vue from 'vue';
|
2 |
|
3 | const ToastConstructor = Vue.extend(require('./toast.vue'));
|
4 | let toastPool = [];
|
5 |
|
6 | let getAnInstance = () => {
|
7 | if (toastPool.length > 0) {
|
8 | let instance = toastPool[0];
|
9 | toastPool.splice(0, 1);
|
10 | return instance;
|
11 | }
|
12 | return new ToastConstructor({
|
13 | el: document.createElement('div')
|
14 | });
|
15 | };
|
16 |
|
17 | let returnAnInstance = instance => {
|
18 | if (instance) {
|
19 | toastPool.push(instance);
|
20 | }
|
21 | };
|
22 |
|
23 | let removeDom = event => {
|
24 | if (event.target.parentNode) {
|
25 | event.target.parentNode.removeChild(event.target);
|
26 | }
|
27 | };
|
28 |
|
29 | ToastConstructor.prototype.close = function() {
|
30 | this.visible = false;
|
31 | this.$el.addEventListener('transitionend', removeDom);
|
32 | this.closed = true;
|
33 | returnAnInstance(this);
|
34 | };
|
35 |
|
36 | let Toast = (options = {}) => {
|
37 | let duration = options.duration || 3000;
|
38 |
|
39 | let instance = getAnInstance();
|
40 | instance.closed = false;
|
41 | clearTimeout(instance.timer);
|
42 | instance.message = typeof options === 'string' ? options : options.message;
|
43 | instance.position = options.position || 'middle';
|
44 | instance.className = options.className || '';
|
45 | instance.iconClass = options.iconClass || '';
|
46 |
|
47 | document.body.appendChild(instance.$el);
|
48 | Vue.nextTick(function() {
|
49 | instance.visible = true;
|
50 | instance.$el.removeEventListener('transitionend', removeDom);
|
51 | ~duration && (instance.timer = setTimeout(function() {
|
52 | if (instance.closed) return;
|
53 | instance.close();
|
54 | }, duration));
|
55 | });
|
56 | return instance;
|
57 | };
|
58 |
|
59 | export default Toast;
|