核心代码

import { useIntersectionObserver } from "@vueuse/core";
// 图片懒加载
export const lazyPlugin = {
  install(app) {
    // 自定义指令:
    app.directive("img-lazy", {
      mounted(el, binding) {

        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }], observerElement) => {
            if (isIntersecting) {
              //图片进入视觉入口了
              el.src = binding.value;
              stop();
            }
          }
        );
      },
    });
  },
};

使用

<img v-img-lazy="baseUrl + item.url" alt="" :key="item.url" />

要点:

**一定要加上:key,不然会出现在更新数据源的时候,数据更新图片被缓存不更新的情况**

ClearBoth
25 声望3 粉丝

Hello World!