dialog.js 2.2KB

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