用 vue写一个懒加载
时间: 2024-05-11 09:17:14 浏览: 14
好的,以下是一个简单的 Vue 懒加载组件示例:
```html
<template>
<div>
<div v-if="showComponent">
<!-- 需要懒加载的组件 -->
</div>
<div v-else>
<!-- 加载中的提示 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
showComponent: false,
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
// 判断组件是否在可视区域内
const componentPosition = this.$el.getBoundingClientRect();
if (
componentPosition.top >= 0 &&
componentPosition.bottom <=
(window.innerHeight || document.documentElement.clientHeight)
) {
// 加载组件
this.showComponent = true;
// 移除滚动事件监听器
window.removeEventListener("scroll", this.handleScroll);
}
},
},
};
</script>
```
这个组件会在页面滚动到该组件所在位置时加载组件,可以有效减少页面加载时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)