dialog.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. transition: 'scale',
  14. customStyle: '',
  15. messageAlign: '',
  16. overlayStyle: '',
  17. confirmButtonText: '确认',
  18. cancelButtonText: '取消',
  19. showConfirmButton: true,
  20. showCancelButton: false,
  21. closeOnClickOverlay: false,
  22. confirmButtonOpenType: '',
  23. };
  24. let currentOptions = Object.assign({}, defaultOptions);
  25. function getContext() {
  26. const pages = getCurrentPages();
  27. return pages[pages.length - 1];
  28. }
  29. const Dialog = (options) => {
  30. options = Object.assign(Object.assign({}, currentOptions), options);
  31. return new Promise((resolve, reject) => {
  32. const context = options.context || getContext();
  33. const dialog = context.selectComponent(options.selector);
  34. delete options.context;
  35. delete options.selector;
  36. if (dialog) {
  37. dialog.setData(
  38. Object.assign({ onCancel: reject, onConfirm: resolve }, options)
  39. );
  40. wx.nextTick(() => {
  41. dialog.setData({ show: true });
  42. });
  43. queue.push(dialog);
  44. } else {
  45. console.warn(
  46. '未找到 van-dialog 节点,请确认 selector 及 context 是否正确'
  47. );
  48. }
  49. });
  50. };
  51. Dialog.alert = (options) => Dialog(options);
  52. Dialog.confirm = (options) =>
  53. Dialog(Object.assign({ showCancelButton: true }, options));
  54. Dialog.close = () => {
  55. queue.forEach((dialog) => {
  56. dialog.close();
  57. });
  58. queue = [];
  59. };
  60. Dialog.stopLoading = () => {
  61. queue.forEach((dialog) => {
  62. dialog.stopLoading();
  63. });
  64. };
  65. Dialog.currentOptions = currentOptions;
  66. Dialog.defaultOptions = defaultOptions;
  67. Dialog.setDefaultOptions = (options) => {
  68. currentOptions = Object.assign(Object.assign({}, currentOptions), options);
  69. Dialog.currentOptions = currentOptions;
  70. };
  71. Dialog.resetDefaultOptions = () => {
  72. currentOptions = Object.assign({}, defaultOptions);
  73. Dialog.currentOptions = currentOptions;
  74. };
  75. Dialog.resetDefaultOptions();
  76. export default Dialog;