toast.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 = (typeof options.context === 'function'
  26. ? options.context()
  27. : options.context) || getContext();
  28. const toast = context.selectComponent(options.selector);
  29. if (!toast) {
  30. console.warn('未找到 van-toast 节点,请确认 selector 及 context 是否正确');
  31. return;
  32. }
  33. delete options.context;
  34. delete options.selector;
  35. toast.clear = () => {
  36. toast.setData({ show: false });
  37. if (options.onClose) {
  38. options.onClose();
  39. }
  40. };
  41. queue.push(toast);
  42. toast.setData(options);
  43. clearTimeout(toast.timer);
  44. if (options.duration != null && options.duration > 0) {
  45. toast.timer = setTimeout(() => {
  46. toast.clear();
  47. queue = queue.filter((item) => item !== toast);
  48. }, options.duration);
  49. }
  50. return toast;
  51. }
  52. const createMethod = (type) => (options) => Toast(Object.assign({ type }, parseOptions(options)));
  53. Toast.loading = createMethod('loading');
  54. Toast.success = createMethod('success');
  55. Toast.fail = createMethod('fail');
  56. Toast.clear = () => {
  57. queue.forEach((toast) => {
  58. toast.clear();
  59. });
  60. queue = [];
  61. };
  62. Toast.setDefaultOptions = (options) => {
  63. Object.assign(currentOptions, options);
  64. };
  65. Toast.resetDefaultOptions = () => {
  66. currentOptions = Object.assign({}, defaultOptions);
  67. };
  68. export default Toast;