一、图片懒加载的原理
二、Vue中实现图片懒加载
2.1 使用vue-lazyload插件
2.1.1 安装插件
首先,你需要在项目中安装vue-lazyload插件:
npm install vue-lazyload --save
2.1.2 引入并注册插件
在Vue项目的入口文件(例如main.js)中引入vue-lazyload并注册:
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
2.1.3 使用v-lazy指令
<template>
<img v-lazy="imageUrl" alt="图片描述">
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/image.jpg'
}
}
}
</script>
2.2 使用IntersectionObserver API
<template>
<img v-for="(image, index) in images" :key="index" v-intersection="handleIntersection" alt="图片描述">
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const images = ref([
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
])
const loadedImages = ref([])
function handleIntersection(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting && !loadedImages.value.includes(entry.target.src)) {
entry.target.src = entry.target.dataset.src
loadedImages.value.push(entry.target.src)
}
})
observer.unobserve(entry.target)
}
return {
images,
handleIntersection
}
}
}
</script>