美文网首页
Vue实现图片懒加载

Vue实现图片懒加载

作者: 搬码人 | 来源:发表于2023-08-21 14:56 被阅读0次

引言

一篇文章可能包含文字内容与插图,当进入一篇文章的网页时img默认会立即记载图片,而我们希望没浏览到图片位置时不要加载图片,节约性能。那就要用到图片懒加载。

图片懒加载

  • 首先创建指令

在main.js中

  • 自定义指令的使用
<template>
<p>狗</p>
<p>狗</p>
<p>狗</p>
<p>狗</p>
<div v-for="item in imgs" :key="item.id">
    <img v-lazy :src="item.src">
</div>
</template>
<script setup>
import {ref} from 'vue'
const imgs = ref([
    {id:1,src:"https://img2.baidu.com/it/u=748323254,2144431882&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"},
    {id:2,src:"https://img2.pconline.com.cn/pconline/0706/07/1031072_070611dog10.jpg"},
    {id:3,src:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw%2F8cb77051-a424-4b25-b339-41de6550d56f%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1695276380&t=d7e8035571fa912ae25277aba92f61ff"}
])
</script>

<style scoped>
p{
    height: 100px;
}
img{
    height: 200px;
    width: 200px;
    object-fit: contain;
}
</style>
  • 懒加载详情
export default{
    mounted(el){
        const imgSrc = el.src
        el.src = ''
        const observer = new IntersectionObserver(([{isIntersecting}])=>{
            //元素出现在可视区域 或 离开可视区域 触发
            if(isIntersecting){
                //加载图片
                el.src = imgSrc
                //停止观察
                observer.unobserve(el)
            }
        })

        observer.observe(el)
    }
}

1、 此处的指令应用于img,所以这里el就特指img。
2、 挂载完成后先将img的src保存,然后置空img的src不让其加载资源。
3、 利用IntersectionObserver实现监听,这里解构出isIntersecting属性用于判断元素是否进入可视区域。
4、 当图片加载完成后停止监听。

相关文章

网友评论

      本文标题:Vue实现图片懒加载

      本文链接:https://www.haomeiwen.com/subject/qkxymdtx.html