lazy-image.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { useRect } from "@vant/use";
  2. import { loadImageAsync } from "./util.mjs";
  3. import { noop } from "../../utils/index.mjs";
  4. import { h } from "vue";
  5. var stdin_default = (lazyManager) => ({
  6. props: {
  7. src: [String, Object],
  8. tag: {
  9. type: String,
  10. default: "img"
  11. }
  12. },
  13. render() {
  14. var _a, _b;
  15. return h(
  16. this.tag,
  17. {
  18. src: this.renderSrc
  19. },
  20. (_b = (_a = this.$slots).default) == null ? void 0 : _b.call(_a)
  21. );
  22. },
  23. data() {
  24. return {
  25. el: null,
  26. options: {
  27. src: "",
  28. error: "",
  29. loading: "",
  30. attempt: lazyManager.options.attempt
  31. },
  32. state: {
  33. loaded: false,
  34. error: false,
  35. attempt: 0
  36. },
  37. renderSrc: ""
  38. };
  39. },
  40. watch: {
  41. src() {
  42. this.init();
  43. lazyManager.addLazyBox(this);
  44. lazyManager.lazyLoadHandler();
  45. }
  46. },
  47. created() {
  48. this.init();
  49. this.renderSrc = this.options.loading;
  50. },
  51. mounted() {
  52. this.el = this.$el;
  53. lazyManager.addLazyBox(this);
  54. lazyManager.lazyLoadHandler();
  55. },
  56. beforeUnmount() {
  57. lazyManager.removeComponent(this);
  58. },
  59. methods: {
  60. init() {
  61. const { src, loading, error } = lazyManager.valueFormatter(this.src);
  62. this.state.loaded = false;
  63. this.options.src = src;
  64. this.options.error = error;
  65. this.options.loading = loading;
  66. this.renderSrc = this.options.loading;
  67. },
  68. checkInView() {
  69. const rect = useRect(this.$el);
  70. return rect.top < window.innerHeight * lazyManager.options.preLoad && rect.bottom > 0 && rect.left < window.innerWidth * lazyManager.options.preLoad && rect.right > 0;
  71. },
  72. load(onFinish = noop) {
  73. if (this.state.attempt > this.options.attempt - 1 && this.state.error) {
  74. if (process.env.NODE_ENV !== "production" && !lazyManager.options.silent) {
  75. console.log(
  76. `[@vant/lazyload] ${this.options.src} tried too more than ${this.options.attempt} times`
  77. );
  78. }
  79. onFinish();
  80. return;
  81. }
  82. const { src } = this.options;
  83. loadImageAsync(
  84. { src },
  85. ({ src: src2 }) => {
  86. this.renderSrc = src2;
  87. this.state.loaded = true;
  88. },
  89. () => {
  90. this.state.attempt++;
  91. this.renderSrc = this.options.error;
  92. this.state.error = true;
  93. }
  94. );
  95. }
  96. }
  97. });
  98. export {
  99. stdin_default as default
  100. };