vue的图片懒加载

**安装:**vueuse 插件

npm i @vueuse/core
搜索: useIntersectionObserver 方法

复制代码
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

export default {
  setup() {
    const target = ref(null)
    const targetIsVisible = ref(false)

    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }], observerElement) => {
        targetIsVisible.value = isIntersecting
      },
    )

    return {
      target,
      targetIsVisible,
    }
  },
}

使用:

main.js:

1、引入方法

复制代码
// 用来图片懒加载
import { useIntersectionObserver } from "@vueuse/core";

2、提前配置好 自定义指令

复制代码
// 全局指令
app.directive("img-lazy", {
  mounted(el, binding) {
    console.log(el, binding.value);
    const { stop } = useIntersectionObserver(
      el,
      ([{ isIntersecting }], observerElement) => {
        console.log(isIntersecting);
        if (isIntersecting) {
          el.src = binding.value;
          stop()     //避免性能浪费,视口可见后不再监听
        }
      }
    );
  },
});

html部分:

复制代码
 <li v-for="item in list" :key="item.id">
        <RouterLink to="/">
          <img alt="" v-img-lazy="item.picture" />
          <p class="name">{{ item.name }}</p>
          <p class="price">&yen;{{ item.price }}</p>
        </RouterLink>
      </li>

useIntersectionObserver 方法可以获取元素是否在视口区域内,在的话就是true,不在就是flase

相关推荐
中微子40 分钟前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
秋田君1 小时前
深入理解JavaScript设计模式之命令模式
javascript·设计模式·命令模式
中微子2 小时前
React 状态管理 源码深度解析
前端·react.js
风吹落叶花飘荡3 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript
加减法原则3 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele3 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4533 小时前
React移动端开发项目优化
前端·react.js·前端框架
天若有情6733 小时前
React、Vue、Angular的性能优化与源码解析概述
vue.js·react.js·angular.js
你的人类朋友3 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维
web_Hsir3 小时前
vue3.2 前端动态分页算法
前端·算法