toast.js 1.83 KB
Newer Older
程默 committed
1
import { isObj } from '../common/validator';
李嘉林 committed
2
const defaultOptions = {
程默 committed
3 4 5 6 7 8 9 10 11 12
  type: 'text',
  mask: false,
  message: '',
  show: true,
  zIndex: 1000,
  duration: 2000,
  position: 'middle',
  forbidClick: false,
  loadingType: 'circular',
  selector: '#van-toast',
李嘉林 committed
13 14 15 16
};
let queue = [];
let currentOptions = Object.assign({}, defaultOptions);
function parseOptions(message) {
程默 committed
17
  return isObj(message) ? message : { message };
李嘉林 committed
18 19
}
function getContext() {
程默 committed
20 21
  const pages = getCurrentPages();
  return pages[pages.length - 1];
李嘉林 committed
22 23
}
function Toast(toastOptions) {
程默 committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
  const options = Object.assign(
    Object.assign({}, currentOptions),
    parseOptions(toastOptions)
  );
  const context = options.context || getContext();
  const toast = context.selectComponent(options.selector);
  if (!toast) {
    console.warn('未找到 van-toast 节点,请确认 selector 及 context 是否正确');
    return;
  }
  delete options.context;
  delete options.selector;
  toast.clear = () => {
    toast.setData({ show: false });
    if (options.onClose) {
      options.onClose();
李嘉林 committed
40
    }
程默 committed
41 42 43 44 45 46 47 48 49 50 51
  };
  queue.push(toast);
  toast.setData(options);
  clearTimeout(toast.timer);
  if (options.duration != null && options.duration > 0) {
    toast.timer = setTimeout(() => {
      toast.clear();
      queue = queue.filter((item) => item !== toast);
    }, options.duration);
  }
  return toast;
李嘉林 committed
52
}
程默 committed
53 54
const createMethod = (type) => (options) =>
  Toast(Object.assign({ type }, parseOptions(options)));
李嘉林 committed
55 56 57 58
Toast.loading = createMethod('loading');
Toast.success = createMethod('success');
Toast.fail = createMethod('fail');
Toast.clear = () => {
程默 committed
59 60 61 62
  queue.forEach((toast) => {
    toast.clear();
  });
  queue = [];
李嘉林 committed
63 64
};
Toast.setDefaultOptions = (options) => {
程默 committed
65
  Object.assign(currentOptions, options);
李嘉林 committed
66 67
};
Toast.resetDefaultOptions = () => {
程默 committed
68
  currentOptions = Object.assign({}, defaultOptions);
李嘉林 committed
69 70
};
export default Toast;