当前位置: 首页 > ops >正文

vue3自定义指令来实现 v-lazyImg 功能

v-lazyImg

在 Vue 3 中,可以通过自定义指令来实现v-lazyImg 功能
  • 新建一个名为 lazyImg.ts 的文件,在其中定义一个名为 lazyImg 的自定义指令。
import type { Directive, DirectiveBinding ,App} from 'vue'
import errorImg from './errorSrc.png' // 导入默认错误图片// 交互动画选项配置
let options: {root: HTMLElement | nullthreshold: number
} | null// 交互动画实例
let observer: IntersectionObserver | null = null// 交互动画回调函数,用于处理图片懒加载逻辑
const callback: IntersectionObserverCallback = (entries) => {entries.forEach((entry) => {if (entry.isIntersecting) { // 判断元素是否进入视口const target = entry.target as HTMLImageElement // 获取目标元素(图片let img = target.dataset.src || '' // 从 data-src 属性获取图片真实地址// 图片加载函数const loadImage = (url: string) => {const image = new Image() image.src = url// 图片加载成功image.onload = () => {console.log('图片加载成功');   target.src = urlobserver?.unobserve(target)}// 图片加载失败image.onerror = () => {target.src = errorImgobserver?.unobserve(target)console.log('图片加载失败')}}loadImage(img)}})
}
// 观察处理函数,用于处理指令绑定逻辑
const observerHandler: (el: Element, binding: DirectiveBinding) => void = (el,binding,
) => {if (el.tagName !== 'IMG')returnconst { value } = binding // 获取指令绑定的值el.setAttribute('data-src', String(value)) // 将图片地址存储在 data-src 属性中observer?.observe(el)  // 开始观察元素
}// Vue 自定义指令对象,用于实现图片懒加载功能
const vImgLazyLoad: Directive = {// 在组件卸载前移除观察器,避免内存泄漏beforeUnmount(el: HTMLElement) {if (observer)observer.unobserve(el)},// 在指令绑定到元素时初始化观察器并开始观察mounted(el: HTMLElement, binding:DirectiveBinding) {if (options === null) {options = {root: document.querySelector('html'),  // 视口参考元素threshold: 0.1,  // 元素进入视口 10% 时触发回调}}if (observer === null)  // 创建交互动画实例observer = new IntersectionObserver(callback, options)observerHandler(el, binding)},// 在指令绑定值更新时重新绑定观察逻辑updated(el: HTMLElement, binding: DirectiveBinding) {observerHandler(el, binding)},
}
// 导出函数用于在 Vue 应用中注册指令
export const setupLazyImgDirective = (app: App<Element>) => {app.directive('lazyImg', vImgLazyLoad)}
export default vImgLazyLoad
  • 在 main.ts 中导入directive/index.ts并注册指令。
// directive/index.ts
import type { App } from 'vue'
import {setupLazyImgDirective} from './lazyImg'/*** 导出指令:v-xxx* @methods lazyImg 懒加载图片,用法: v-lazyImg="xxx"*/export const setupPermission = (app: App<Element>) => {setupLazyImgDirective(app)
}
  • vue 组件中中使用
<script setup lang="ts">import {ref} from "vue";const list = Array.from({ length: 100 }).map((_, i) => ({id: i,img: 'https://img1.baidu.com/it/u=837510728,3756639739&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800'}))
</script><template><imgv-for="item in list":key="item.id"v-lazyImg="item.img":style="{ width: '100px', height: '100px', display: 'block' }"/>
</template>
http://www.xdnf.cn/news/9034.html

相关文章:

  • IP地址查询的重要性
  • 01 NLP的发展历程和挑战
  • 第2章 程序设计语言基础知识
  • C#编解码:Base64扩展类的实现与应用
  • 人工智能如何协助老师做课题
  • 电子电路:什么是感应电动势?
  • C++ 模板函数深度指南
  • 【CF】Day66——Edu 168.D + CF 853 (Div. 2).C (树 + 二分 + 贪心 | 组合数学)
  • 佰力博科技与您探讨铁电分析仪具有哪些测试功能
  • [PyMySQL]
  • reflect-metadata作用
  • Ubuntu | NVIDIA 驱动、CUDA 与 cuDNN 的安装与配置 / 常见问题及解决方法
  • Zabbix集成Grfana自定义仪表盘
  • World of Warcraft [CLASSIC] Jewelcrafting Gemstone 3 [80 WLK]
  • 初等数论--Garner‘s 算法
  • 邻近标记技术(PL):探索生物分子相互作用的前沿工具
  • Java设计模式之适配器模式
  • AI时代新词-多模态(Multimodal)
  • 测评机构如何通过漏扫保障软件安全?扫描范围与局限解析
  • leetcode:2235. 两整数相加(python3解法,数学相关算法题)
  • 十六进制字符转十进制算法
  • C++——STL——unordered_map与unordered_set的使用以及使用哈希表封装unordered_map/set
  • https的进化之路(八卦版)
  • JVM 深度解析
  • k-way Hypergraph Partitioning via n-Level Recursive Bisection【2016 ALENEX】文献总结
  • N2语法 时间
  • 协同过滤实现电影推荐
  • 931. 用三种不同颜色为网格涂色
  • 力扣刷题(第三十八天)
  • Rk3568驱动开发_设备树点亮LED_11