vue3 使用intersectionobserver实现懒加载
时间: 2023-12-29 07:03:15 浏览: 197
Vue 3 中可以使用 Intersection Observer API 来实现懒加载。Intersection Observer API 可以观察一个元素是否进入了视口(viewport)或者离开了视口。
首先,你需要创建一个指令来实现懒加载:
```javascript
const lazyLoad = {
mounted(el, binding) {
let options = {
rootMargin: '0px',
threshold: 0.1
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
binding.value();
observer.unobserve(el);
}
});
}, options);
observer.observe(el);
}
}
export default lazyLoad;
```
在这个指令中,我们使用了 Intersection Observer API 来观察元素是否进入了视口。当元素进入视口时,我们会调用指令传入的回调函数。
接下来,在组件中使用这个指令:
```html
<template>
<div class="container">
<img v-lazyload="loadImage" :data-src="imageUrl" />
</div>
</template>
<script>
import lazyLoad from "@/directives/lazyLoad";
export default {
directives: {
lazyload: lazyLoad
},
data() {
return {
imageUrl: "https://example.com/image.jpg"
};
},
methods: {
loadImage() {
const img = new Image();
img.onload = () => {
this.$el.setAttribute("src", this.imageUrl);
this.$el.removeAttribute("data-src");
};
img.src = this.imageUrl;
}
}
};
</script>
```
在这个例子中,我们在图片上使用指令 `v-lazyload`,并且传入了一个回调函数 `loadImage`。当图片进入视口时,指令会调用 `loadImage` 函数来加载图片。
在 `loadImage` 函数中,我们创建一个新的 `Image` 对象,并设置其 `onload` 回调函数。当图片加载完成时,我们将图片的 `src` 属性设置为 `imageUrl`,并移除 `data-src` 属性,以此来显示图片。
希望这个例子可以帮助你实现 Vue 3 中的懒加载。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)