vue3+ts实现图片懒加载
时间: 2023-07-25 22:08:18 浏览: 193
在 Vue3 中,可以使用 `Intersection Observer` 实现图片的懒加载。下面是一个使用 TypeScript 实现的图片懒加载示例:
安装 `intersection-observer` 库:
```bash
npm install intersection-observer --save
```
创建一个 `LazyImage` 组件:
```vue
<template>
<img :src="placeholder" :data-src="src" />
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import 'intersection-observer';
export default defineComponent({
props: {
src: {
type: String,
required: true,
},
placeholder: {
type: String,
default: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=',
},
},
setup(props) {
const imageRef = ref<HTMLImageElement | null>(null);
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target as HTMLImageElement;
img.src = img.dataset.src || '';
observer.unobserve(img);
}
});
});
onMounted(() => {
if (imageRef.value) {
observer.observe(imageRef.value);
}
});
return {
imageRef,
};
},
});
</script>
```
在父组件中使用 `LazyImage` 组件:
```vue
<template>
<div>
<lazy-image src="https://example.com/image1.jpg" />
<lazy-image src="https://example.com/image2.jpg" />
<lazy-image src="https://example.com/image3.jpg" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import LazyImage from './LazyImage.vue';
export default defineComponent({
components: {
LazyImage,
},
});
</script>
```
`LazyImage` 组件中,使用 `Intersection Observer` 监听图片是否进入视野,如果进入视野,则加载图片;如果未进入视野,则不加载图片,以此实现图片懒加载的效果。
阅读全文