uniapp 封装 List列表

652 阅读2分钟

封装原因

项目中多个页面使用了list列表展示数据,但是list数据列表中有许多东西是可以复用的,例如

  • 没有更多了 的展示
  • 暂无数据 的展示

代码

<template>
	<div :style="props.listBoxStyle">
		<template v-if="!props.isNotData">
			<slot></slot>
			<slot name="finish" v-if="props.isFinish">
				<div class="finish">{{ props.finishText }}</div>
			</slot>
		</template>
		<slot name="notData" v-else>
			<div class="not-data">
				<image
					src="https://tui.tongbu.com/images/history/pic_blank_udid_nodata.png"
					mode="aspectFit"
				/>
				<text>{{ props.notDataText }}</text>
			</div>
		</slot>
	</div>
</template>

<script setup>
	const props = defineProps({
		isFinish: {
			required: true,
		},
		finishText: {
			type: String,
			default: '数据加载完了',
		},
		isNotData: {
			required: true,
		},
		notDataText: {
			type: String,
			default: '暂无数据',
		},
		listBoxStyle: {
			type: Object,
		},
	});
</script>

<style lang="scss" scoped>
	.finish {
		padding: 20rpx 0;
		color: #ccc;
		text-align: center;
	}
	.not-data {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
		}
		text {
			font-size: 32rpx;
			font-weight: 400;
			color: #666666;
		}
	}
</style>

页面使用

<myList :isFinish="isFinish" :isNotData="isNotData">
			<!-- 默认插槽:展示数据 -->
			<div class="list-item" v-for="(item, index) in list" :key="index">
				<text>{{ item.name }}</text>
			</div>
			<!-- 数据加载完成插槽 -->
			<template #finish>数据加载完成了~~~</template>
			<!-- 暂无数据插槽 -->
			<template #notData>暂无数据</template>
		</myList>
                
        import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
                
                let page = ref(1);
	const limit = ref(10);
	const isFinish = ref(false); // 是否加载完成
	const isNotData = ref(false); // 是否没有数据
	const list = ref([]);
	async function getList() {
		try {
			// 模拟发起请求 开始
			let res = [];
			let i = list.value.length;
			for (let index = 0; index < limit.value; index++) {
				res.push({
					id: i + index,
					name: '列表' + (i + index + 1),
				});
			}
			if (list.value.length == 20) {
				res.pop();
			}
			// 模拟发起请求 结束
			if (page.value == 1) {
				list.value = res;
			} else {
				list.value.push(...res);
			}
			isFinish.value = res.length < limit.value;
			isNotData.value = list.value.length == 0;
		} catch (error) {
			console.log('获取列表失败', error);
		}
	}
	onReachBottom(() => {
		if (isFinish.value) return;
		page.value++;
		getList();
	});
	onPullDownRefresh(async () => {
		page.value = 1;
		await getList();
		uni.stopPullDownRefresh();
	});
        

注意事项

  • onPullDownRefresh, onReachBottom是uniapp的事件
  • 使用list组件的页面 需要在pages.json文件中将页面下拉属性开启:"enablePullDownRefresh": true

tip

因为list组件只是把共用的东西,例如:加载完成、暂无数据 这些每个list列表都会有的东西进行封装,只是为了减少相似代码的重复编写

但是具体的展示内容以及获取数据的逻辑可能每个页面都不一样,所以数据的展示、数据的请求只能页面自己根据需求相应的进行编写