我需要一段vue2滚动加载更多的代码
时间: 2024-03-24 12:36:12 浏览: 15
好的,下面是一个基于Vue2实现的滚动加载更多的代码示例:
```vue
<template>
<div class="scroll-container" ref="scrollContainer">
<div v-for="(item, index) in list" :key="index">{{ item }}</div>
<div v-if="loading">加载中...</div>
<div v-else-if="!noMore">上拉加载更多</div>
<div v-else>没有更多了</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [], // 列表数据
page: 1, // 当前页码
limit: 10, // 每页条数
loading: false, // 是否正在加载数据
noMore: false // 是否没有更多数据了
}
},
mounted() {
this.initScroll()
this.loadData()
},
methods: {
initScroll() {
const scrollContainer = this.$refs.scrollContainer
scrollContainer.addEventListener('scroll', () => {
const scrollHeight = scrollContainer.scrollHeight
const scrollTop = scrollContainer.scrollTop
const clientHeight = scrollContainer.clientHeight
if (scrollTop + clientHeight >= scrollHeight) {
this.loadMore()
}
})
},
async loadData() {
// 初始化加载数据
this.loading = true
const data = await this.getData(this.page, this.limit)
this.list = data
this.page++
this.loading = false
},
async loadMore() {
// 加载更多数据
if (this.loading || this.noMore) {
return
}
this.loading = true
const data = await this.getData(this.page, this.limit)
if (data.length === 0) {
this.noMore = true
} else {
this.list = [...this.list, ...data]
this.page++
}
this.loading = false
},
// 模拟异步获取数据
getData(page, limit) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Array.from({ length: limit }, (_, index) => `第 ${page} 页,第 ${index + 1} 条数据`))
}, 1000)
})
}
}
}
</script>
```
该代码使用了一个滚动容器`scroll-container`,通过监听滚动事件来实现滚动加载更多的效果。`list`数组是列表数据,`page`和`limit`分别表示当前页码和每页条数。`loading`和`noMore`分别表示是否正在加载和是否没有更多数据了。在`mounted`钩子中初始化滚动容器并加载第一页数据,`initScroll`方法用于初始化滚动事件监听。`loadData`方法用于初始化加载数据,`loadMore`方法用于加载更多数据。`getData`方法模拟异步获取数据的过程。