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>
相关推荐
map_3d_vis9 分钟前
百度地图地图类型切换:普通地图、卫星图、混合图
前端·javascript·地图·百度地图
BruceVan40 分钟前
给 AI 配上 Context7:查文档更准,还更省 token
vue.js·spring boot·ai编程
FYKJ_201010 小时前
springboot众创项目团队管理系统94666-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·spark·课程设计
圆心角11 小时前
代码也有折旧率
前端·程序员
CoderYanger11 小时前
Java EE 进阶:14.案例综合练习-博客系统(第二弹):博客详情+令牌技术
服务器·前端·spring boot·后端·spring·java-ee·github
FYKJ_201014 小时前
springboot贫困生认定管理系统59009-计算机毕业设计、课程设计
java·javascript·vue.js·spring boot·后端·django·课程设计
kyriewen15 小时前
我测了 5 种关页上报,两种老写法一条都没发出去
前端·javascript·程序员
不一样的少年_17 小时前
受够了当人肉传话筒:我把这 9 个 Agent 塞进了同一个聊天框
前端·agent·ai编程
狗头大军之江苏分军18 小时前
《潮水漫过十七岁》 加一个蛋,顺便说一下我解放了
前端·后端
Captaincc18 小时前
掘金AI用量迎来重大更新!全新AI用量
前端·后端