1、在实现滚动监听的DOM元素上绑定ref值
<div class="list-page"
ref="scrollRef">
<div class="item"
v-for="(item,index) in cardData"
:key="index">
<el-card>
<div class="card-header">
<div class="title">
<span>{{ item.userName }}</span>
<p>{{ item.carPlate }}</p>
</div>
</el-card>
<div class="loading"
v-if="loading">到底了</div>
</div>
</div>
2、在onMounted生命周期中绑定监听事件,当滚动条滚动到底部的时候加载数据
var cardData = ref<any>([])
const scrollRef = ref() //名字需要跟上面模板中定义的一样
onMounted(async () => {
await getList()
if (scrollRef.value) {
// 给元素添加滚动监听器
scrollRef.value.addEventListener('scroll', handleScroll, true)
// 如果你需要在组件卸载时移除监听器,可以返回一个清理函数
return () => {
scrollRef.value.removeEventListener('scroll', handleScroll, true)
}
}
})
const handleScroll = async (e: any) => {
scrollTopVal.value = e.target.scrollTop
let offsetHeight = e.target.offsetHeight
let scrollHeight = e.target.scrollHeight
if (scrollTopVal.value + offsetHeight >= scrollHeight) {
//滚动条到达底部
if (cardData.value.length < total.value) {
//数据为加载完,继续赋值
serarchData.pageNum++
const res = await unreplyApi(serarchData)
if (res.data.code == 200) {
let arr = res.data.rows
})
cardData.value = [...cardData.value, ...arr]
}
}
}
}
const loading: any = computed(() => {
cardData.value.length >= total.value
})