index.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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() {
  42. return new Promise((resolve, reject) => {
  43. const poster = this.selectComponent('#poster');
  44. if (this.downloadStatus && this.downloadStatus !== 'fail') {
  45. if (this.downloadStatus === 'success') {
  46. resolve();
  47. } else {
  48. this.once('downloadSuccess', () => resolve());
  49. this.once('downloadFail', (e) => reject(e));
  50. }
  51. } else {
  52. poster.downloadResource(this.data.config.images)
  53. .then(() => {
  54. this.downloadStatus = 'success';
  55. resolve();
  56. })
  57. .catch((e) => reject(e));
  58. }
  59. })
  60. },
  61. onCreate() {
  62. !this.data.hideLoading && wx.showLoading({ mask: true, title: '生成中' });
  63. return this.downloadResource().then(() => {
  64. // !this.data.hideLoading && wx.hideLoading();
  65. const poster = this.selectComponent('#poster');
  66. poster.create(this.data.config);
  67. })
  68. .catch((err) => {
  69. !this.data.hideLoading && wx.hideLoading();
  70. wx.showToast({ icon: 'none', title: err.errMsg || '生成失败' });
  71. console.error(err);
  72. this.triggerEvent('fail', err);
  73. })
  74. },
  75. onCreateSuccess(e) {
  76. const { detail } = e;
  77. this.triggerEvent('success', detail);
  78. },
  79. onCreateFail(err) {
  80. console.error(err);
  81. this.triggerEvent('fail', err);
  82. }
  83. }
  84. })