一、前言
二、代码的实现
import { useToast } from '@/uni_modules/wot-design-uni'
export const useList = (
api: (params: any) => Promise<any>,
search: object = {},
isLoading: boolean = false,
) => {
const page = reactive<{ page: number; size: number }>({ page: 1, size: 10 })
const state = ref<'loading' | 'finished' | 'error'>('loading')
const total = ref<number>()
const listData = ref([])
const toast = useToast()
const getInitList = async (isUp = false) => {
try {
if (isLoading) toast.loading({ loadingType: 'ring', msg: '加载中...' })
const res = await api({ search, page })
if (isUp) {
listData.value = res.data.length > 0 ? listData.value.concat(res.data) : []
} else {
page.page = 1
listData.value = res.data
}
total.value = res.page.total
state.value = listData.value.length < total.value ? 'loading' : 'finished'
} catch (error) {
console.error(error)
state.value = 'error'
} finally {
if (isLoading) toast.close()
}
}
const loadData = () => {
state.value = 'loading'
if (listData.value.length < total.value) {
page.page++
getInitList(true)
} else {
page.page = 1
state.value = 'finished'
}
}
return {
listData,
getInitList,
loadData,
state,
}
}
三、代码的使用
<scroll-view :scroll-y="true" style="height: calc(100vh - 280rpx)" @scrolltolower="loadData">
<view class="p-12px mt-40rpx">
<view v-if="listData && listData.length">
<dynamic-list :list="listData" @delete="handleDelete"></dynamic-list>
<wd-loadmore
:state="state"
loading-text="正在努力加载..."
finished-text="没有更多了~"
error-text="网络出错了"
></wd-loadmore>
</view>
<view class="pt-112rpx" v-else>
<status-tip tip="暂无信息数据~"></status-tip>
</view>
</view>
</scroll-view>
import { useList } from '@/hooks/useList'
import { getDynamics } from '@/service/my'
const companyMemberId = computed(() => {
return userStore.userInfo.companyMemberId
})
const search = reactive({
companyMemberId,
dynamicsType: '400',
})
const { getInitList, listData, loadData, state } = useList(getDynamics, search)
onLoad(() => {
getInitList()
})
四、简单解释
- getInitList: 请求的方法
- listData: 请求返回来的数据
- loadData: 触底刷新的方法
- state: 加载效果的变化,结合wd-loadmore使用
- getDynamics: 请求的api
- search: 要传的参数
- 希望对你有帮助,有问题也欢迎提出,有不合理的地方,也望谅解,我只是一个入行不久,努力学习的程序媛