【Vue】图片懒加载的实现

封装全局指令img-lazy

js 复制代码
// 定义懒加载插件
import { useIntersectionObserver } from '@vueuse/core'

export const lazyPlugin = {
  install (app) {
    // 懒加载指令逻辑
    app.directive('img-lazy', {
      mounted (el, binding) {
        // el: 指令绑定的那个元素 img
        // binding: binding.value  指令等于号后面绑定的表达式的值  图片url
        console.log(el, binding.value)
        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }]) => {
            console.log(isIntersecting)
            if (isIntersecting) {
              // 进入视口区域
              el.src = binding.value
              stop()
            }
          },
        )
      }
    })
  }
}

注册全局指令

js 复制代码
// 全局指令注册
import {lazyPlugin} from "@/directives";
app.use(lazyPlugin)

重构HomeHot.vue,从而实现懒加载效果,提高页面加载性能

html 复制代码
  <ul class="goods-list">
    <li v-for="item in hotList" :key="item.id">
      <RouterLink to="/">
        <img v-img-lazy="item.picture" alt="">
        <p class="name">{{ item.title }}</p>
        <p class="desc">{{ item.alt }}</p>
      </RouterLink>
    </li>
  </ul>

有一点需要说明:IntersectionObserver是异步库,这样即使目标元素一开始就在视口中,回调函数的执行也会在解构赋值之后,这样能够确保stop方法在回调函数中调用时已经被正确解构。

相关推荐
梦梦代码精1 天前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
刘一说1 天前
Vue3 组合式 API(Composition API):逻辑复用的革命性实践
vue.js·vue
seabirdssss1 天前
《bootstrap is not defined 导致“获取配置详情失败”?一次前端踩坑实录》
前端·bootstrap·html
kgduu1 天前
js之表单
开发语言·前端·javascript
摘星编程1 天前
React Native for OpenHarmony 实战:Picker 选择器组件详解
javascript·react native·react.js
摘星编程1 天前
React Native for OpenHarmony 实战:VirtualizedList 虚拟化列表
javascript·react native·react.js
谢尔登1 天前
Vue3 响应式系统——computed 和 watch
前端·架构
愚公移码1 天前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
摘星编程1 天前
React Native for OpenHarmony 实战:RefreshControl 下拉刷新组件
javascript·react native·react.js
欣然~1 天前
法律案例 PDF 批量转 TXT 工具代码
linux·前端·python