dialog.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = (typeof options.context === 'function'
  34. ? options.context()
  35. : options.context) || getContext();
  36. const dialog = context.selectComponent(options.selector);
  37. delete options.context;
  38. delete options.selector;
  39. if (dialog) {
  40. dialog.setData(Object.assign({ callback: (action, instance) => {
  41. action === 'confirm' ? resolve(instance) : reject(instance);
  42. } }, options));
  43. wx.nextTick(() => {
  44. dialog.setData({ show: true });
  45. });
  46. queue.push(dialog);
  47. }
  48. else {
  49. console.warn('未找到 van-dialog 节点,请确认 selector 及 context 是否正确');
  50. }
  51. });
  52. };
  53. Dialog.alert = (options) => Dialog(options);
  54. Dialog.confirm = (options) => Dialog(Object.assign({ showCancelButton: true }, options));
  55. Dialog.close = () => {
  56. queue.forEach((dialog) => {
  57. dialog.close();
  58. });
  59. queue = [];
  60. };
  61. Dialog.stopLoading = () => {
  62. queue.forEach((dialog) => {
  63. dialog.stopLoading();
  64. });
  65. };
  66. Dialog.currentOptions = currentOptions;
  67. Dialog.defaultOptions = defaultOptions;
  68. Dialog.setDefaultOptions = (options) => {
  69. currentOptions = Object.assign(Object.assign({}, currentOptions), options);
  70. Dialog.currentOptions = currentOptions;
  71. };
  72. Dialog.resetDefaultOptions = () => {
  73. currentOptions = Object.assign({}, defaultOptions);
  74. Dialog.currentOptions = currentOptions;
  75. };
  76. Dialog.resetDefaultOptions();
  77. export default Dialog;