在vue3中手写按需加载图片

在我们的网页中.假如使用了大量的图片,每个图片都是需要去访问加载的
这就影响了我们的访问速度,手写一个按需加载组件,就可以解决这个问题
让图片处于页面视图的时候再加载,减轻网页访问负担

利用vue3官网给出的钩子
我们常用的就是onMountent
如官网所示

为了及时监测,这里使用vueUse来进行检测视图是否包含监控组件/标签
el代表的是标签本身,bing是代表了标签的值,一般用binding.value表示
isIntersecting代表监控的组件是否出现在视图中

app.directive('img-lazy',{
        mounted(el, binding) {
          // console.log(el);
         const {stop}=  useIntersectionObserver(
            el,
            ([{ isIntersecting }]) => {
              // console.log(isIntersecting);
              if(isIntersecting){
              // console.log(binding.value);
              console.log("el",el)
              el.src = binding.value
              stop()
              }
            },
          )
        },
      }

标签用v-img-lazy表示,在使用过程视图会反复出现这个懒加载进而出现重加载问题,那么我们引入vueuse内置的stop函数来进行预防,确保只执行一次
2.为了实现单一功能,我们另开一个文件,在main.js中使用vue.use(导入的该插件)

新开一个directives/index.js

import { useIntersectionObserver } from '@vueuse/core'


export  const lazyLand = {
   install(app){
    app.directive('img-lazy',{
        mounted(el, binding) {
          // console.log(el);
         const {stop}=  useIntersectionObserver(
            el,
            ([{ isIntersecting }]) => {
              // console.log(isIntersecting);
              if(isIntersecting){
              // console.log(binding.value);
              console.log("el",el)
              el.src = binding.value
              stop()
              }
            },
          )
        },
      })
   }

}
posted @   浮白呀  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示