只需传入 请求方法 和请求参数,
即可实现:
① 下拉刷新
② 触底请求下一页
③ 触底 没有更多 提示(借助iView, 可改)
1、封装组件:
<template>
<scroll-view scroll-y="true" class="scroll-Y"
:style="{backgroundColor: bgc}"
refresher-enabled
:refresher-triggered="refreshListFlag"
@refresherrefresh="refreshList"
@refresherrestore="onRestore"
@scrolltolower="scrolltolower"
>
<slot name="list" :list="list"></slot>
<u-loadmore style="margin: 20px" :status="lowerStatus" v-if="list.length > 0"/>
</scroll-view>
</template>
<script>
import {mapGetters} from "vuex";
export default {
// 调用组件的父盒子要有固定高度
name: "cusScrollViewList",
props: {
// 请求方法
requestFun: {
type: Function,
},
// 其他请求参数(默认请求只有页码)
otherParams: {
type: Object,
default: () => {}
},
// 背景色
bgc: {
type: String,
default: '#eeeeee'
}
},
computed: {
lowerStatus() {
return this.pageSize.total == (this.list ? this.list.length : 0) ? 'nomore' : 'loadmore'
}
},
data() {
return {
pageSize: {
pn: 1,
ps: 10,
total: 0,
},
list: [],
refreshListFlag: false, // 刷新状态
}
},
created() {
console.log('created')
this.getList()
},
methods: {
/**
* @description 请求列表
* @param { Boolean } push 是否向列表数组里push而不是赋值
*/
async getList(push) {
if(this.list) {
if(this.pageSize.total == this.list.length && this.list.length != 0) {
uni.showToast({
icon: "none",
title: "没有更多了",
duration: 700
});
this.refreshListFlag = false
this.lowerFlag = false
return
}
}
const res = await this.requestFun( Object.assign({ ps: 10, pn: this.pageSize.pn}, this.otherParams) )
if(res.code === '0000') {
if(push) {
this.setList([...this.list, ...res.list], )
} else {
this.setList(res.list)
}
this.pageSize.total = res.total
} else {
this.setList()
this.list = []
uni.showToast({
icon: "none",
title: res.msg
})
}
this.refreshListFlag = false
this.lowerFlag = false
},
setList(list = []) {
this.list = list
},
// 刷新列表
async refreshList(tips) {
if (this.refreshListFlag) return;
this.refreshListFlag = true;
this.resetParams()
await this.getList()
},
resetParams() {
this.setList()
this.pageSize.pn = 1
this.pageSize.total = 0
},
// 刷新完成调用,不存在会报错
onRestore() {
uni.showToast({
icon: "none",
title: "刷新成功",
duration: 700
});
},
scrolltolower(e) {
this.pageSize.pn ++
this.getList(true)
},
},
beforeDestroy() {
this.resetParams()
}
}
</script>
<style scoped>
.scroll-Y {
height: 100%;
}
</style>
2、调用示例:
<template>
<div style="height: 100vh;">
<cus-scroll-view-list :request-fun="temFun">
<template #list="{ list }">
<div v-for="(item, index) in list" :key="index">
<div @click="goDetail(item)">
<list-item :item="item"/>
</div>
</div>
</template>
</cus-scroll-view-list>
</div>
</template>
<script>
import CusScrollViewList from "../components/cusScrollViewList";
export default {
components: {ListItem, CusScrollViewList},
data() {
return {
temFun: () => {
return {
code: '0000',
total: 1,
list: [
{label: '张三'}
]
}
}
}
},
methods: {
goDetail(item) {
console.log(item)
}
}
}
</script>
<style scoped>
</style>