效果:
vue_scroll
1. template:使用原生scroll方法
<section
class="popover_main"
@scroll="scrollHandle">
<div
class="main_item"
v-for="item in list"
:key="item.id"
@click="itemClickHandle(item)">
<p >{{ item.title }}</p>
<p>{{ item.content }}</p>
<p>{{ item.dateTime}}</p>
</div>
<p v-if="loading" class="bottom_text"><i class="el-icon-loading" /><span>加载中...</span></p>
<p v-if="noMore" class="bottom_text">没有更多了</p>
</section>
2.js中:
data(){
return{
pages: {
current: 1,
size: 20
},
noMore: false,
loading: false,
}
}
scrollHandle(e) {
if (this.noMore || this.loading) return
const { scrollTop, scrollHeight, clientHeight } = e.target
console.log('🚀 ~ scrollHandle ~ scrollTop, scrollHeight, clientHeight:', scrollTop, scrollHeight, clientHeight)
if (scrollTop + clientHeight === scrollHeight) {
this.pages.current++
this.getHistoreMessage(1)
}
},
我们需要从原生DOM对象中结构scrollTop, scrollHeight, clientHeight这三个参数
我们依次解释一下这个这是三个属性的意思
scrollTop:是从元素顶部到其最顶部可见内容的距离的度量。当元素的内容不生成垂直滚动条时,其scrollTop值为0
当前这个可视元素在DOM中是第三个元素
我们查看两个元素的高度分别为120和80
我们打印出来最新的log中scrollTop的值正好是200
所以我们现在理解scrollTop的定义大家应该就理解了
scrollHeight 指元素全部内容的高度,包括溢出隐藏的部分;
所以scrollHeight = 我们所有class="main_item"的高度之和
clientHeight 则是元素可见区域的高度,不包括滚动条。
顾名思义就是当前class="popover_main"的高度500px
当我们滚动条滚动掉底部的时候打印:
所以我们可以根据这个公式判断到滚动条滚动条到底部了。
scrollTop + clientHeight = scrollHeight
loadingType是用来判断,如果是初次加载此接口则不需要合并数组,滚动分页请求的则需求合并数组
async getHistoreMessage(loadingType = 0) {
try {
loadingType ? this.loading = true : this.pageLoading = true
const params = {
current: this.pages.current,
size: this.pages.size
}
const { code, data } = await httpMsgQueryList(params)
loadingType ? this.loading = false : this.pageLoading = false
if (code === 200) {
const dataList = data.records
loadingType
? this.historeMsgList = [...this.historeMsgList, ...dataList]
: this.historeMsgList = dataList
//如果接口中的数据 小于 传过来的size 则说明没数据了,下次滚动就不请求数据了
if (data.records.length < this.pages.size) {
this.noMore = true
}
}
} catch (error) {
console.log('🚀 ~ getHistoreMessage ~ error:', error)
}
}
大家可以根据以上的代码进行适当的拓展,根据业务需求来定。