cache-image.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <template>
  2. <image class="img" :src="img_url" :style="mstyle" mode="aspectFill"></image>
  3. </template>
  4. <script>
  5. export default {
  6. name: 'cache-image',
  7. props: {
  8. src: {
  9. type: String,
  10. default: ''
  11. },
  12. mstyle: {
  13. type: String,
  14. default: ''
  15. },
  16. ext: {
  17. type: String,
  18. default: 'gif'
  19. }
  20. },
  21. data() {
  22. return {
  23. img_url: ''
  24. };
  25. },
  26. watch: {
  27. src: {
  28. handler: async function (n) {
  29. if (!n) return;
  30. let isCache = await this.isCache(this.filename);
  31. if (isCache) {
  32. this.img_url = this.filename;
  33. } else {
  34. this.img_url = n;
  35. this.createDownload();
  36. }
  37. },
  38. immediate: true
  39. }
  40. },
  41. computed: {
  42. filename() {
  43. let filename = `_doc/IM_emoji_pack/${this.src.replace(/\./g, '_').replace(/\//g, '_')}.${this.ext}`;
  44. return filename;
  45. }
  46. },
  47. methods: {
  48. // 判断是否已经缓存
  49. isCache(filePath) {
  50. return new Promise((r) => {
  51. uni.getFileInfo({
  52. filePath,
  53. success: (res) => {
  54. if (res.errMsg === 'getFileInfo:ok') {
  55. return r(true);
  56. }
  57. return r(false);
  58. },
  59. fail: (e) => {
  60. return r(false);
  61. }
  62. });
  63. });
  64. },
  65. // 下载存储
  66. createDownload() {
  67. let dtask = plus.downloader.createDownload(
  68. this.src,
  69. {
  70. filename: this.filename
  71. },
  72. //
  73. (download, status) => {
  74. if (status == 200) {
  75. let image = download.options.filename; //设置的名字
  76. // this.image = download.filename; //实际生成的名字
  77. // 将本地URL路径转换成平台绝对路径
  78. this.img_url = plus.io.convertLocalFileSystemURL(image);
  79. } else {
  80. this.img_url = src;
  81. }
  82. }
  83. );
  84. dtask.start();
  85. // 下载进度
  86. // dtask.addEventListener('statechanged', function (task, status) {});
  87. }
  88. }
  89. };
  90. </script>