用element的dialog封装图片下滑加载更多的组件
以下是基于Element UI的Dialog组件封装图片下滑加载更多的组件示例代码:
<template>
<div>
<el-dialog
:visible.sync="dialogVisible"
title="图片下滑加载更多"
:width="dialogWidth"
:before-close="handleDialogClose"
>
<div class="image-list" ref="imageList">
<div v-for="(image, index) in imageList" :key="index" class="image-item">
<img :src="image" @load="handleImageLoad(index)" />
</div>
</div>
<div v-if="isLoading" class="loading">加载中...</div>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
dialogVisible: false,
dialogWidth: "90%",
imageList: [], // 图片列表
isLoading: false, // 是否正在加载
loadedIndexes: [], // 已加载的图片索引
lastScrollTop: 0, // 上次滚动条位置
};
},
methods: {
/**
* 打开对话框
*/
openDialog() {
this.dialogVisible = true;
this.loadMore();
},
/**
* 关闭对话框
*/
closeDialog() {
this.dialogVisible = false;
this.imageList = [];
this.loadedIndexes = [];
this.lastScrollTop = 0;
},
/**
* 处理对话框关闭前事件
* @param {function} done - 关闭对话框的回调函数
*/
handleDialogClose(done) {
this.closeDialog();
done();
},
/**
* 处理图片加载完成事件
* @param {number} index - 图片索引
*/
handleImageLoad(index) {
this.loadedIndexes.push(index);
if (this.loadedIndexes.length === this.imageList.length) {
this.isLoading = false; // 所有图片均已加载完成
}
},
/**
* 加载更多图片
*/
loadMore() {
this.isLoading = true; // 开始加载
const startIndex = this.imageList.length; // 下一个图片的索引
const endIndex = startIndex + 9; // 每次加载10张图片
for (let i = startIndex; i < endIndex && i < this.allImages.length; i++) {
this.imageList.push(this.allImages[i]);
}
},
/**
* 处理滚动事件
*/
handleScroll() {
const scrollTop = this.$refs.imageList.scrollTop; // 获取滚动条位置
const scrollHeight = this.$refs.imageList.scrollHeight; // 获取可滚动区域高度
const clientHeight = this.$refs.imageList.clientHeight; // 获取可视区域高度
if (scrollTop > this.lastScrollTop && scrollTop + clientHeight >= scrollHeight) {
// 向下滚动到底部
if (this.loadedIndexes.length < this.imageList.length) {
// 还有未加载完成的图片
this.loadMore();
}
}
this.lastScrollTop = scrollTop;
},
},
mounted() {
// 监听滚动事件
this.$refs.imageList.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
// 移除滚动事件监听
this.$refs.imageList.removeEventListener("scroll", this.handleScroll);
},
};
</script>
<style scoped>
.image-list {
height: 400px;
overflow-y: scroll;
}
.image-item {
display: inline-block;
width: 200px;
margin: 10px;
text-align: center;
}
.loading {
text-align: center;
margin-top: 10px;
}
</style>
使用方法:
在父组件中引入该组件并注册为局部组件,然后在需要使用的地方添加一个按钮或链接,绑定点击事件,调用该组件的openDialog方法即可:
<template>
<div>
<button @click="openImageList">打开图片列表</button>
<image-list-dialog ref="imageListDialog" />
</div>
</template>
<script>
import ImageListDialog from "@/components/ImageListDialog";
export default {
components: {
ImageListDialog,
},
methods: {
openImageList() {
this.$refs.imageListDialog.openDialog();
},
},
};
</script>
``
原文地址: https://www.cveoy.top/t/topic/g3Nx 著作权归作者所有。请勿转载和采集!