vue实现触底加载
触底加载的实现方法
在Vue中实现触底加载功能,可以通过监听滚动事件或使用Intersection Observer API来实现。以下是两种常见的方法:
监听滚动事件
在组件中监听滚动事件,计算滚动位置判断是否触底。
<template>
<div class="container" @scroll="handleScroll">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
loading: false,
page: 1
}
},
methods: {
handleScroll(e) {
const container = e.target
const scrollHeight = container.scrollHeight
const scrollTop = container.scrollTop
const clientHeight = container.clientHeight
if (scrollHeight - scrollTop <= clientHeight + 50 && !this.loading) {
this.loadMore()
}
},
loadMore() {
this.loading = true
// 模拟异步加载数据
setTimeout(() => {
const newData = Array(10).fill(0).map((_, i) => ({
id: this.list.length + i,
content: `内容 ${this.list.length + i}`
}))
this.list = [...this.list, ...newData]
this.page++
this.loading = false
}, 1000)
}
},
mounted() {
this.loadMore()
}
}
</script>
<style>
.container {
height: 500px;
overflow-y: auto;
}
</style>
使用Intersection Observer API
这种方法更现代,性能更好,不需要频繁计算滚动位置。
<template>
<div class="container">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div ref="loader" v-if="!finished">{{ loading ? '加载中...' : '' }}</div>
<div v-if="finished">没有更多了</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
loading: false,
page: 1,
finished: false
}
},
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.loading && !this.finished) {
this.loadMore()
}
})
observer.observe(this.$refs.loader)
},
loadMore() {
this.loading = true
// 模拟异步加载数据
setTimeout(() => {
const newData = Array(10).fill(0).map((_, i) => ({
id: this.list.length + i,
content: `内容 ${this.list.length + i}`
}))
this.list = [...this.list, ...newData]
this.page++
this.loading = false
// 模拟数据加载完毕
if (this.page > 5) {
this.finished = true
}
}, 1000)
}
},
mounted() {
this.loadMore()
this.initObserver()
}
}
</script>
<style>
.container {
height: 500px;
overflow-y: auto;
}
</style>
使用第三方库
也可以使用现成的Vue指令或组件来实现触底加载,例如:
npm install vue-infinite-loading
使用示例:
<template>
<div class="container">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadMore"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: {
InfiniteLoading
},
data() {
return {
list: [],
page: 1
}
},
methods: {
loadMore($state) {
setTimeout(() => {
const newData = Array(10).fill(0).map((_, i) => ({
id: this.list.length + i,
content: `内容 ${this.list.length + i}`
}))
this.list = [...this.list, ...newData]
this.page++
if (this.page > 5) {
$state.complete()
} else {
$state.loaded()
}
}, 1000)
}
},
mounted() {
this.loadMore()
}
}
</script>
注意事项
- 节流处理:滚动事件需要节流处理,避免频繁触发
- 加载状态管理:确保不会重复触发加载
- 数据加载完毕处理:需要显示"没有更多数据"的提示
- 错误处理:网络请求失败时需要提供重试机制
- 移动端适配:需要考虑移动端的滚动行为差异






