index.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. Component({
  2. properties: {
  3. config: {
  4. type: Object,
  5. value: {},
  6. },
  7. preload: { // 是否预下载图片资源
  8. type: Boolean,
  9. value: false,
  10. },
  11. hideLoading: { // 是否隐藏loading
  12. type: Boolean,
  13. value: false,
  14. }
  15. },
  16. ready() {
  17. if (this.data.preload) {
  18. const poster = this.selectComponent('#poster');
  19. this.downloadStatus = 'doing';
  20. poster.downloadResource(this.data.config.images).then(() => {
  21. this.downloadStatus = 'success';
  22. this.trigger('downloadSuccess');
  23. }).catch((e) => {
  24. this.downloadStatus = 'fail';
  25. this.trigger('downloadFail', e);
  26. });
  27. }
  28. },
  29. methods: {
  30. trigger(event, data) {
  31. if (this.listener && typeof this.listener[event] === 'function') {
  32. this.listener[event](data);
  33. }
  34. },
  35. once(event, fun) {
  36. if (typeof this.listener === 'undefined') {
  37. this.listener = {};
  38. }
  39. this.listener[event] = fun;
  40. },
  41. downloadResource(reset) {
  42. return new Promise((resolve, reject) => {
  43. if (reset) {
  44. this.downloadStatus = null;
  45. }
  46. const poster = this.selectComponent('#poster');
  47. if (this.downloadStatus && this.downloadStatus !== 'fail') {
  48. if (this.downloadStatus === 'success') {
  49. resolve();
  50. } else {
  51. this.once('downloadSuccess', () => resolve());
  52. this.once('downloadFail', (e) => reject(e));
  53. }
  54. } else {
  55. poster.downloadResource(this.data.config.images)
  56. .then(() => {
  57. this.downloadStatus = 'success';
  58. resolve();
  59. })
  60. .catch((e) => reject(e));
  61. }
  62. })
  63. },
  64. onCreate(reset = false) {
  65. !this.data.hideLoading && wx.showLoading({ mask: true, title: '生成中' });
  66. return this.downloadResource(typeof reset === 'boolean' && reset).then(() => {
  67. !this.data.hideLoading && wx.hideLoading();
  68. const poster = this.selectComponent('#poster');
  69. poster.create(this.data.config);
  70. })
  71. .catch((err) => {
  72. !this.data.hideLoading && wx.hideLoading();
  73. wx.showToast({ icon: 'none', title: err.errMsg || '生成失败' });
  74. console.error(err);
  75. this.triggerEvent('fail', err);
  76. })
  77. },
  78. onCreateSuccess(e) {
  79. const { detail } = e;
  80. this.triggerEvent('success', detail);
  81. },
  82. onCreateFail(err) {
  83. console.error(err);
  84. this.triggerEvent('fail', err);
  85. }
  86. }
  87. })