在做滚动条滑到底部时有自动加载更多这个需求。
<template>
<div class="content" ref="scroll" @scroll="loadMore">
<ul>
<li v-for="(book, index) in books" :key="index" >
<van-swipe-cell :before-close="beforeClose" :name="book.bookId">
<van-card
:desc=book.bookInfo
:title=book.bookName
class="goods-card"
:thumb=book.bookCover
:id="book.bookId"
/>
<template #right>
<van-button square text="删除" type="danger" class="delete-button" />
</template>
</van-swipe-cell>
</li>
</ul>
<div @click="more">加载更多</div>
</div>
</template>
但是发现循环出来的li标签足够多,撑满一页,页面滚动的时候并不能触发到scrollEvent,是什么原因呢?
猜想应该是滚动事件并不是在我 <div class="content" ref="scroll" @scroll="loadMore">这个div上触发的,因为滚动条并没有出现在我这个div上。这个div完全被li标签撑起来了,产生滚动事件的就是document了
有两种解决办法
第一 就是给content 加固定的高度;
第二就是用fixed定位:
.content {
position: fixed;
top: 50px;
left: 0;
right: 0;
bottom: 0;
overflow: auto
}
上下左右的位置都固定了,所以div自然也就有了固定高度,此方法适用于页面有一个固定高度的头部导航,我项目中有一个50px高的头部导航,所以我采用了fixed定位
下面是加载更多的方法
loadMore(){
clearTimeout(this.timer)
this.timer = setTimeout(()=>{
let { scrollTop,clientHeight,scrollHeight} = this.$refs.scroll;
if(scrollTop+clientHeight+20>scrollHeight){
this.getBooks();
}
},13)
},