dialog.js 2.4 KB

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