Vant-list的二次封装
场景:在写项目需求的时候,移动端有用到vant-list组件。后续需求更新说要对列表数据页加搜索和筛选的功能。发现每次筛选完得在页面内手动重置一次查询参数。不方便,所以封了一层。
二次封装代码
javascript
<template>
<van-list
v-model:loading="loading"
:finished="finished"
@load="handleLoad"
>
<div :class="listClass">
<slot
v-for="item in listData"
:key="item.id"
v-bind="item"
/>
</div>
<div v-if="loadOnce && !listData?.length" class="layout-list__empty">暂无数据</div>
</van-list>
</template>
<script setup>
const props = defineProps({
request: {},
listClass: {},
pageSize: {
type: Number,
default: 10,
},
});
const listData = ref([]);
const loading = ref(false);
const finished = ref(false);
const loadOnce = ref(false);
let pageNum = 0;
let requesting = false;
const handleLoad = async () => {
if (requesting || unref(finished)) { return }
requesting = true;
++pageNum;
const formContent = {
page: pageNum,
pageSize: props.pageSize,
};
const { total, data } = await props.request(formContent);
unref(listData).push(...data);
loadOnce.value = true;
if (!unref(listData).length || unref(listData).length >= total) {
finished.value = true;
}
loading.value = false;
requesting = false;
};
const resetSearch = () => {
listData.value = [];
loading.value = false;
finished.value = false;
loadOnce.value = false;
pageNum = 0;
requesting = false;
handleLoad();
};
defineExpose({
resetSearch,
});
</script>
<style lang="scss" scoped>
.layout-list {
&__empty {
padding: 12px 0;
color: #666;
text-align: center;
}
}
</style>
组件使用
javascript
<mb-search
@updated-search="updatedSearch"
/>
<mb-list
ref="mbListRef"
v-slot="item"
:request="getList(() => (loadForm))"
>
<div>内容</div>
</mb-list>
<script setup>
import { getList } from '@/services/activiti/instance';
defineProps({
selectTypeList: {
type: Array,
default: () => [],
},
});
const mbListRef = ref();
const loadForm = ref({
title: '',
defName: '',
instStatus: 'running',
});
function updatedSearch(title) {
loadForm.value.title = title;
mbListRef.value.resetSearch();
}
</script>