一、需求目标:
列表数据量较大,一次性展示不完,但又希望全量展示,需滚动分页加载
二、关键代码:
<div class="scroll-list" ref="listRef" ="handelScroll" v-loading="state.loading"><p v-for="(item,index) in state.list :key='index'> {{item.name}}</p></div>const listRef = ref(null)const getList = async()=>{const querys = {page:state.page,limit:state.limit}if(state.loading){return false}state.loading = true;const data = await getList(querys)if (data.list && data.list.length > 0 && state.list.length < data.total) {state.list = state.list.concat(data.list);}state.listTotal = data.total;state.loading = false;}// 滚动分页const handelScroll = () =>{const scrollDistance = listRef.value.scrollHeight - listRef.value.scrollTop - listRef.value.clientHeightconst scrollTop = listRef.value.scrollHeight;if (scrollDistance <= 0) {setTimeout(() => {// list 的总长度小于总条数时继续加载if (state.list.length < state.listTotal) {// 添加判断 避免滚动过快 上次加载未渲染完if(state.loading){return false}state.page++;getList()listRef.value.scrollTop = scrollTop;} else {}}, 300)}}.scroll-list {height: 360px;overflow-y: auto;
}
三、寄语:
无论海角与天涯
大抵心安即是家