问星数据小程序

toast.js 1.8KB

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