poster.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <template>
  2. <view>
  3. <view @tap="onCreate">
  4. <slot/>
  5. </view>
  6. <we-canvas ref="poster" @success="onCreateSuccess" @fail="onCreateFail"/>
  7. </view>
  8. </template>
  9. <script>
  10. import WeCanvas from "./index.vue";
  11. export default {
  12. components: {
  13. WeCanvas
  14. },
  15. props: {
  16. config: {
  17. type: Object,
  18. default: {}
  19. },
  20. preload: {
  21. // 是否预下载图片资源
  22. type: Boolean,
  23. default: false
  24. }
  25. },
  26. data() {
  27. return {};
  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.$refs.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
  56. .downloadResource(this.config.images)
  57. .then(() => {
  58. this.downloadStatus = "success";
  59. resolve();
  60. })
  61. .catch(e => reject(e));
  62. }
  63. });
  64. },
  65. onCreate(reset = false) {
  66. return this.downloadResource(typeof reset === "boolean" && reset)
  67. .then(() => {
  68. uni.hideLoading();
  69. const poster = this.$refs.poster;
  70. poster.create(this.config);
  71. })
  72. .catch(err => {
  73. uni.hideLoading();
  74. uni.showToast({ icon: "none", title: err.errMsg || "生成失败" });
  75. console.error(err);
  76. this.$emit("fail", err);
  77. });
  78. },
  79. onCreateSuccess(path) {
  80. this.$emit("success", path);
  81. },
  82. onCreateFail(err) {
  83. console.error(err);
  84. this.$emit("fail", err);
  85. },
  86. },
  87. onReady() {
  88. if (this.preload) {
  89. const poster = this.$refs.poster;
  90. this.downloadStatus = 'doing';
  91. poster.downloadResource(this.config.images).then(() => {
  92. this.downloadStatus = 'success';
  93. this.trigger('downloadSuccess');
  94. }).catch((e) => {
  95. this.downloadStatus = 'fail';
  96. this.trigger('downloadFail', e);
  97. });
  98. }
  99. },
  100. };
  101. </script>
  102. <style lang="scss">
  103. </style>