后端返回大量数据,前端进行懒加载显示
<template>
<div>
<ul class="info" id="info" @scroll="onScroll">
<li v-for="(item, index) in displayList" :key="index">{{ item }}</li>
<li class="tip" v-if="loading">加载中...</li>
<li class="tip" v-else>没有更多了</li>
</ul>
</div>
</template>
<script>
import _throttle from 'lodash/throttle'
export default {
data() {
return {
list: [], // 原数据列表
displayList: [],// 展示数据列表
loading: true, // 控制下拉显示文字
page: 1, // 当前显示0~29
max: 1 // 最多显示多少页码
}
},
created() {
for (let i = 0; i < 301; i++) {
this.list.push(this.list.length + 1)
this.max = Math.ceil(this.list.length / 30)
this.displayList = this.list.slice((this.page - 1) * 30, this.page * 30)
console.log(this.max)
}
},
methods: {
// 滚动触发事件
onScroll: _throttle(function () {
var info = document.getElementById('info')
var scrollTop = info.scrollTop
var clientHeight = info.clientHeight
var scrollHeight = info.scrollHeight
if (scrollHeight - clientHeight < scrollTop + 20) {
if (this.displayList.length >= this.list.length) {
this.loading = false
return
} else {
this.addList()
}
}
}, 2000),
// 改变展示数据
addList() {
this.loading = true
setTimeout(() => {
if (this.page < this.max) {
this.page++
const info = this.list.slice((this.page - 1) * 30, this.page * 30)
this.displayList = [...this.displayList, ...info]
}
}, 1000)
}
}
}
</script>
<style scoped>
ul {
width: 300px;
height: 550px;
overflow: auto;
list-style: none;
margin: 10px;
padding: 0;
border: 1px solid gray;
overflow-anchor: none;
}
li {
line-height: 30px;
}
li:nth-of-type(odd) {
margin: 0;
padding: 0;
background: rgb(228, 245, 245);
}
li:last-child {
background: white;
}
.tip {
color: gainsboro;
text-align: center;
}
</style>
// 如果上述代码无法运行,请先安装lodash
命令:npm i --save lodash