dialog.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. let queue = [];
  2. const defaultOptions = {
  3. show: false,
  4. title: '',
  5. width: null,
  6. theme: 'default',
  7. message: '',
  8. zIndex: 100,
  9. overlay: true,
  10. selector: '#van-dialog',
  11. className: '',
  12. asyncClose: false,
  13. beforeClose: null,
  14. transition: 'scale',
  15. customStyle: '',
  16. messageAlign: '',
  17. overlayStyle: '',
  18. confirmButtonText: '确认',
  19. cancelButtonText: '取消',
  20. showConfirmButton: true,
  21. showCancelButton: false,
  22. closeOnClickOverlay: false,
  23. confirmButtonOpenType: '',
  24. };
  25. let currentOptions = Object.assign({}, defaultOptions);
  26. function getContext() {
  27. const pages = getCurrentPages();
  28. return pages[pages.length - 1];
  29. }
  30. const Dialog = (options) => {
  31. options = Object.assign(Object.assign({}, currentOptions), options);
  32. return new Promise((resolve, reject) => {
  33. const context = options.context || getContext();
  34. const dialog = context.selectComponent(options.selector);
  35. delete options.context;
  36. delete options.selector;
  37. if (dialog) {
  38. dialog.setData(
  39. Object.assign(
  40. {
  41. callback: (action, instance) => {
  42. action === 'confirm' ? resolve(instance) : reject(instance);
  43. },
  44. },
  45. options
  46. )
  47. );
  48. wx.nextTick(() => {
  49. dialog.setData({ show: true });
  50. });
  51. queue.push(dialog);
  52. } else {
  53. console.warn(
  54. '未找到 van-dialog 节点,请确认 selector 及 context 是否正确'
  55. );
  56. }
  57. });
  58. };
  59. Dialog.alert = (options) => Dialog(options);
  60. Dialog.confirm = (options) =>
  61. Dialog(Object.assign({ showCancelButton: true }, options));
  62. Dialog.close = () => {
  63. queue.forEach((dialog) => {
  64. dialog.close();
  65. });
  66. queue = [];
  67. };
  68. Dialog.stopLoading = () => {
  69. queue.forEach((dialog) => {
  70. dialog.stopLoading();
  71. });
  72. };
  73. Dialog.currentOptions = currentOptions;
  74. Dialog.defaultOptions = defaultOptions;
  75. Dialog.setDefaultOptions = (options) => {
  76. currentOptions = Object.assign(Object.assign({}, currentOptions), options);
  77. Dialog.currentOptions = currentOptions;
  78. };
  79. Dialog.resetDefaultOptions = () => {
  80. currentOptions = Object.assign({}, defaultOptions);
  81. Dialog.currentOptions = currentOptions;
  82. };
  83. Dialog.resetDefaultOptions();
  84. export default Dialog;