toast.js 1.9KB

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