vue实现触底加载
实现触底加载的方法
触底加载是一种常见的分页加载方式,当用户滚动到页面底部时自动加载更多数据。以下是基于Vue的实现方法:
监听滚动事件
在Vue组件中,可以通过监听窗口滚动事件来判断是否触底。在mounted钩子中添加事件监听,在beforeDestroy钩子中移除监听。

mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const windowHeight = document.documentElement.clientHeight || document.body.clientHeight
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
if (scrollTop + windowHeight >= scrollHeight - 50) {
this.loadMore()
}
},
loadMore() {
// 加载更多数据的逻辑
}
}
使用Intersection Observer API
Intersection Observer API提供了一种更高效的方式来监测元素是否进入视口,适合现代浏览器环境。
data() {
return {
observer: null
}
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore()
}
})
this.observer.observe(document.querySelector('#load-more-trigger'))
},
beforeDestroy() {
this.observer.disconnect()
}
结合分页逻辑
触底加载通常需要配合分页逻辑实现,确保每次加载新的数据页。

data() {
return {
page: 1,
pageSize: 10,
isLoading: false,
hasMore: true
}
},
methods: {
async loadMore() {
if (this.isLoading || !this.hasMore) return
this.isLoading = true
try {
const res = await api.getData({
page: this.page,
pageSize: this.pageSize
})
if (res.data.length) {
this.list = [...this.list, ...res.data]
this.page++
} else {
this.hasMore = false
}
} finally {
this.isLoading = false
}
}
}
优化用户体验
为了提升用户体验,可以添加加载状态提示和防抖处理。
<template>
<div>
<!-- 数据列表 -->
<div v-if="isLoading">加载中...</div>
<div v-if="!hasMore">没有更多数据了</div>
</div>
</template>
<script>
import { debounce } from 'lodash'
export default {
methods: {
handleScroll: debounce(function() {
// 滚动处理逻辑
}, 200)
}
}
</script>
使用第三方库
对于复杂场景,可以考虑使用专门的分页加载库,如vue-infinite-loading。
import InfiniteLoading from 'vue-infinite-loading'
export default {
components: {
InfiniteLoading
},
methods: {
async infiniteHandler($state) {
try {
const res = await api.getData({
page: this.page,
pageSize: this.pageSize
})
if (res.data.length) {
this.list.push(...res.data)
this.page++
$state.loaded()
} else {
$state.complete()
}
} catch (err) {
$state.error()
}
}
}
}
以上方法可根据具体需求选择或组合使用,实现高效、用户体验良好的触底加载功能。






