vue 实现下拉滑动触底加载
实现下拉滑动触底加载可以分为以下几个步骤:
-
监听滚动事件,判断是否到达底部。
-
到达底部后,发起数据请求,获取数据。
-
将获取到的数据添加到页面上。
下面是一个基于Vue.js的示例代码:
<template>
<div class="container" ref="container" @scroll="handleScroll">
<ul>
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
page: 1,
pageSize: 10,
loading: false
}
},
methods: {
handleScroll() {
const container = this.$refs.container
const scrollHeight = container.scrollHeight
const scrollTop = container.scrollTop
const clientHeight = container.clientHeight
if (scrollTop + clientHeight >= scrollHeight && !this.loading) {
this.loadMore()
}
},
loadMore() {
this.loading = true
setTimeout(() => {
// 模拟获取数据
const start = (this.page - 1) * this.pageSize
const end = start + this.pageSize
const newData = Array.from({ length: this.pageSize }, (v, k) => `item ${start + k}`)
this.list = [...this.list, ...newData]
this.page++
this.loading = false
}, 1000)
}
}
}
</script>
我们监听了容器的滚动事件,并判断是否到达底部。如果到达底部且当前没有正在加载数据,就发起数据请求获取数据,并将获取到的数据添加到列表中。添加数据时,我们使用了ES6的扩展运算符,将新数据和旧数据合并成一个新的数组。同时,为了避免频繁请求数据,我们使用了loading状态来防止重复触发加载更多的操作。
本文来自博客园,作者:小珍珠在河里敲代码,转载请注明原文链接:https://www.cnblogs.com/Jansens520/p/17268640.html

浙公网安备 33010602011771号