loading.vue
<template>
<div class="main">
<div class="scroll" @scroll="scrollHandle">
<div class="item" v-for="(item, index) in itemList" :key="index">{{ item.name }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
itemList: [],
noMore: false, // 没有更多了
page: 0, // 页数
limit: 15, // 每页长度
index: 0,
isRuning: false
}
},
mounted() {
this.getList()
},
methods: {
getList() {
// 用于判断上接口请求是否结束,如果未结束就return 避免重复请求,页面不断加载
if (this.isRuning) {
return
}
let tempArr = []
this.isRuning = true
setTimeout(() => {
if (this.page < 2) {
for (let index = 0; index < this.limit; index++) {
const obj = { name: `河西镇${++this.index}` }
tempArr.push(obj)
}
} else {
tempArr = []
}
this.itemList.push(...tempArr)
// 当返回的列表长度小于limit则意味着没有更多数据了,noMore设为true
if (tempArr.length < this.limit) {
this.noMore = true
}
this.isRuning = false
}, 1000);
},
scrollHandle(e) {
const element = e.target
// element.scrollTop 当前视图中的实际元素的顶部边缘和顶部边缘之间的距离 滚轮未滚动时为0 滚轮滚动时 此值会改变
// element.scrollHeight 整个元素的高度(包括带滚动条的隐蔽的地方)内容固定时是固定值
// element.clientHeight 看到的所有内容高度 一般为固定值 这里选的是iphoneX机型 height固定为579
if (element.scrollTop + element.clientHeight >= element.scrollHeight - 1) {
console.log('触底');
// srcollTop + 一个可视区高scrollHeight比可滚的所有高度scrollHeight大时触底
if (this.noMore) {
// 没更多数据就提示没有更多了
console.log('没有更多了');
this.isRuning = false
} else {
// 否则触底加载更多数据
this.page += 1
this.getList()
}
}
}
},
}
</script>
<style>
.main {
width: 100vw;
height: 100vh;
overflow: hidden;
}
.scroll {
width: 80vw;
height: 80vh;
margin: 8vh auto;
background-color: #ccc;
overflow-y: scroll;
}
.item {
width: 98%;
height: 50px;
text-align: center;
line-height: 50px;
font-size: larger;
font-weight: 600;
border: 2px solid red;
}
</style>