vue 实现滚动到底部加载更多
时间: 2023-08-31 22:10:36 浏览: 59
要实现滚动到底部加载更多,可以借助 Vue 自带的 `scroll` 事件和一些计算属性。具体实现步骤如下:
1. 在需要滚动的容器上监听 `scroll` 事件。
```html
<template>
<div ref="container" @scroll="handleScroll">
<!-- 列表内容 -->
</div>
</template>
```
2. 在 `handleScroll` 方法中,判断容器滚动到了底部,如果是则触发加载更多的方法。
```js
methods: {
handleScroll() {
const container = this.$refs.container
// 容器滚动到底部
if (container.scrollHeight - container.scrollTop === container.clientHeight) {
this.loadMore()
}
},
loadMore() {
// 加载更多数据
}
}
```
3. 计算当前是否有更多数据需要加载,用于显示加载更多按钮或者提示信息。
```js
computed: {
hasMore() {
return this.list.length < this.total
}
}
```
4. 在模板中根据 `hasMore` 的值来显示加载更多按钮或者提示信息。
```html
<template>
<div ref="container" @scroll="handleScroll">
<!-- 列表内容 -->
<div v-if="hasMore" class="load-more" @click="loadMore">加载更多</div>
<div v-else class="no-more">没有更多数据了</div>
</div>
</template>
```
完整代码示例:
```html
<template>
<div ref="container" @scroll="handleScroll">
<ul>
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
<div v-if="hasMore" class="load-more" @click="loadMore">加载更多</div>
<div v-else class="no-more">没有更多数据了</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [], // 列表数据
total: 0, // 总共的数据量
pageSize: 10, // 每页数据量
currentPage: 1 // 当前页数
}
},
computed: {
hasMore() {
return this.list.length < this.total
}
},
methods: {
handleScroll() {
const container = this.$refs.container
// 容器滚动到底部
if (container.scrollHeight - container.scrollTop === container.clientHeight) {
this.loadMore()
}
},
loadMore() {
// 模拟加载更多数据
setTimeout(() => {
const start = this.pageSize * (this.currentPage - 1)
const end = start + this.pageSize
this.list = this.list.concat(Array.from({ length: this.pageSize }).map((_, i) => `Item ${start + i + 1}`))
this.currentPage++
}, 500)
}
}
}
</script>
```