vue3+ts 图片懒加载

<template>
  <div>
    <div class="div-box">
      <img
        v-lazy="item"
        :src="item"
        v-for="item in arr"
        :key="item"
        alt=""
        width="360"
        height="500"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import type { Directive } from "vue";
import { entries } from "lodash";
// glob 是懒加的模式
// globEager 静态加载
let imageList = import.meta.globEager("./assets/images/*.*");
let imageList2: Record<
  string,
  { default: string }
> = import.meta.glob("./assets/images/*.*", { eager: true });
let arr = Object.values(imageList2).map((v) => v.default);
console.log(imageList, arr, "imageList");

let vLazy: Directive<HTMLImageElement, string> = async (el, binding) => {
  console.log(el, "el");
  const def = await import("./assets/vue.svg");
  el.src = def.default;
  const observe = new IntersectionObserver((entries) => {
    console.log(entries, binding.value);
    if (entries[0].intersectionRatio > 0) {
      setTimeout(() => {
        el.src = binding.value;
      }, 500);
      observe.unobserve(el);
    }
  });
  observe.observe(el);
};
</script>

<style>
.div-box {
  overflow: scroll;
  height: 100vh;
}
</style>

你可能感兴趣的:(vue.js,javascript,前端)