超好用的懒加载插件 ,无需安装,vueuse提供,可配置图片懒加载 数据懒加载

一、图片懒加载

1. src下创建目录directives/index.ts

import { useIntersectionObserver } from "@vueuse/core";
// 默认图片
import defaultImg from "@/assets/images/200.png";
import { App } from "vue";

export default {
  install(app: App) {
    app.directive("lazy", {
      mounted(el, binding) {
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          // isIntersecting 用于判断el元素是否进入可视区
          if (isIntersecting) {
            el.src = binding.value;
            // 错误回调 显示默认图片
            el.onerror = function () {
              this.src = defaultImg;
            };
            stop();
          }
        });
      },
    });
  },
};

2. 页面中使用

<img v-lazy="item.picture" alt="" />

二、数据懒加载

1. src下创建目录hooks/index.ts

import { useIntersectionObserver } from "@vueuse/core";
import { ref } from "vue";

export const useLazyLoad = (callback: () => void) => {
  const target = ref(null);
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    if (isIntersecting) {
      callback();
      stop();
    }
  });
  return target;
};

2. 页面中使用

<script lang="ts" setup name="HomeHot">
import { useLazyLoad } from "@/hooks";
//调用懒加载方法,ref="target"的元素到达可视区时会执行home.getHotGoodsList()函数
const target = useLazyLoad(home.getHotGoodsList);
</script>
<template>
  <div>
    <!-- ref="target"的元素会懒加载 -->
    <HomePanel title="人气推荐" sub-title="人气爆款 不容错过" ref="target">
        
    </HomePanel>
  </div>
</template>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值