Vue 实现
{{ item }} 在 Vue 示例中:
定义了一个组件,其中包含数据items用于展示列表项,bufferSize表示缓冲区大小,isLoading用于标识是否正在加载数据。
在模板中使用v-for循环渲染items数据。
通过@scroll监听滚动事件,在事件处理函数handleScroll中进行滚动距离的计算和判断。
当满足条件时,设置isLoading为true,模拟异步加载数据(使用setTimeout),加载完成后更新items数据并将isLoading设为false。
React 实现
import React, { useState, useEffect, useRef } from'react'; function App() { const [items, setItems] = useState([]); const [isLoading, setIsLoading] = useState(false); const bufferSize = 100; const containerRef = useRef(null); useEffect(() => { // 监听滚动事件 const container = containerRef.current; container.addEventListener('scroll', handleScroll); // 组件卸载时移除滚动事件监听 return () => { container.removeEventListener('scroll', handleScroll); }; }, []); const handleScroll = (event) => { const scrollElement = event.target; const scrollTop = scrollElement.scrollTop; const scrollHeight = scrollElement.scrollHeight; const clientHeight = scrollElement.clientHeight; const distanceToBottom = scrollHeight - (scrollTop + clientHeight); if (distanceToBottom < bufferSize &&!isLoading) { setIsLoading(true); // 模拟加载更多数据 setTimeout(() => { const newItems = []; for (let i = 0; i < 10; i++) { newItems.push(`新数据 ${items.length + i}`); } setItems([...items,...newItems]); setIsLoading(false); }, 1000); } }; return ( containerRef} style={{ height: '500px', overflow: 'auto' }}> {items.map((item, index) => ( index}>{item} ))} ); } export default App; 在 React 示例中:
使用useState钩子定义状态items和isLoading。
使用useRef钩子获取滚动容器的引用。
通过useEffect钩子在组件挂载时添加滚动事件监听,组件卸载时移除监听。
在handleScroll函数中进行滚动距离的计算和加载判断。
当满足条件时,设置isLoading为true,模拟加载数据后更新items状态并将isLoading设为false。
以上就是文章全部内容了,如果喜欢这篇文章的话,还希望三连支持一下,感谢!