Vue图片懒加载

安装 vueuse 插件

npm i @vueuse/core

搜索 useIntersectionObserver 方法
javascript 复制代码
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、引入方法
javascript 复制代码
// 用来图片懒加载
import { useIntersectionObserver } from "@vueuse/core";
2、提前配置好 自定义指令
javascript 复制代码
// 全局指令
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部分:
javascript 复制代码
 <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>
相关推荐
雪芽蓝域zzs35 分钟前
第 5 节:Marker 点击弹出 InfoWindow 信息窗口
vue.js
回眸&啤酒鸭43 分钟前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013841 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员1 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子1 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒1 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend2 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋10212 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
大包子3 小时前
structuredClone vs lodash.cloneDeep:核心差异与选型指南
javascript·vue.js
海码事务所3 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端