vue3 图片懒加载

使用vue第三方库 useIntersectionObserver
创建文件 directives/index.js 导入第三方库
import { useIntersectionObserver } from '@vueuse/core'

export const lazyPlugin = {
  install(app) {
    app.directive('img-lazy', {
      mounted(el, binding) {
        // el:指令绑定的那个元素 img
        // binding: binding.value 指令等于后面绑定的表达式的值
        // console.log(el, binding.value)
        // stop防止重复渲染
        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }]) => {
            // console.log(isIntersecting)
            if (isIntersecting) {
              el.src = binding.value
              stop()
            }
          }
        )
      }
    })
  }
}
main.js引入 挂载
import { lazyPlugin } from './directives'
import App from './App.vue'

const app = createApp(App)
app.use(lazyPlugin)
使用 在需要懒加载的图片标签上添加v-img-lazy属性(注意不需要绑定src了)
index.vue
<img v-img-lazy="item.picture" alt="" />
 
posted @   Happy-P  阅读(288)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示