toast.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict';
  2. var __assign =
  3. (this && this.__assign) ||
  4. function () {
  5. __assign =
  6. Object.assign ||
  7. function (t) {
  8. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9. s = arguments[i];
  10. for (var p in s)
  11. if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  12. }
  13. return t;
  14. };
  15. return __assign.apply(this, arguments);
  16. };
  17. Object.defineProperty(exports, '__esModule', { value: true });
  18. var validator_1 = require('../common/validator');
  19. var defaultOptions = {
  20. type: 'text',
  21. mask: false,
  22. message: '',
  23. show: true,
  24. zIndex: 1000,
  25. duration: 2000,
  26. position: 'middle',
  27. forbidClick: false,
  28. loadingType: 'circular',
  29. selector: '#van-toast',
  30. };
  31. var queue = [];
  32. var currentOptions = __assign({}, defaultOptions);
  33. function parseOptions(message) {
  34. return validator_1.isObj(message) ? message : { message: message };
  35. }
  36. function getContext() {
  37. var pages = getCurrentPages();
  38. return pages[pages.length - 1];
  39. }
  40. function Toast(toastOptions) {
  41. var options = __assign(
  42. __assign({}, currentOptions),
  43. parseOptions(toastOptions)
  44. );
  45. var context = options.context || getContext();
  46. var toast = context.selectComponent(options.selector);
  47. if (!toast) {
  48. console.warn('未找到 van-toast 节点,请确认 selector 及 context 是否正确');
  49. return;
  50. }
  51. delete options.context;
  52. delete options.selector;
  53. toast.clear = function () {
  54. toast.setData({ show: false });
  55. if (options.onClose) {
  56. options.onClose();
  57. }
  58. };
  59. queue.push(toast);
  60. toast.setData(options);
  61. clearTimeout(toast.timer);
  62. if (options.duration != null && options.duration > 0) {
  63. toast.timer = setTimeout(function () {
  64. toast.clear();
  65. queue = queue.filter(function (item) {
  66. return item !== toast;
  67. });
  68. }, options.duration);
  69. }
  70. return toast;
  71. }
  72. var createMethod = function (type) {
  73. return function (options) {
  74. return Toast(__assign({ type: type }, parseOptions(options)));
  75. };
  76. };
  77. Toast.loading = createMethod('loading');
  78. Toast.success = createMethod('success');
  79. Toast.fail = createMethod('fail');
  80. Toast.clear = function () {
  81. queue.forEach(function (toast) {
  82. toast.clear();
  83. });
  84. queue = [];
  85. };
  86. Toast.setDefaultOptions = function (options) {
  87. Object.assign(currentOptions, options);
  88. };
  89. Toast.resetDefaultOptions = function () {
  90. currentOptions = __assign({}, defaultOptions);
  91. };
  92. exports.default = Toast;