您的位置:首页 > 健康 > 养生 > Vue 和 React 框架实现滚动缓冲区

Vue 和 React 框架实现滚动缓冲区

2024/10/7 4:36:41 来源:https://blog.csdn.net/weixin_43891869/article/details/140486504  浏览:    关键词:Vue 和 React 框架实现滚动缓冲区

Vue 实现

<template><div id="app" @scroll="handleScroll"><!-- 页面内容 --><div v-for="item in items" :key="item">{{ item }}</div></div>
</template><script>
export default {data() {return {items: [],bufferSize: 100,isLoading: false,};},methods: {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 < this.bufferSize &&!this.isLoading) {this.isLoading = true;// 模拟加载更多数据setTimeout(() => {for (let i = 0; i < 10; i++) {this.items.push(`新数据 ${this.items.length + i}`);}this.isLoading = false;}, 1000);}},},
};
</script><style>
#app {height: 500px;overflow: auto;
}
</style>

在 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 (<div ref={containerRef} style={{ height: '500px', overflow: 'auto' }}>{items.map((item, index) => (<div key={index}>{item}</div>))}</div>);
}export default App;

在 React 示例中:
使用useState钩子定义状态items和isLoading。
使用useRef钩子获取滚动容器的引用。
通过useEffect钩子在组件挂载时添加滚动事件监听,组件卸载时移除监听。
在handleScroll函数中进行滚动距离的计算和加载判断。
当满足条件时,设置isLoading为true,模拟加载数据后更新items状态并将isLoading设为false。

以上就是文章全部内容了,如果喜欢这篇文章的话,还希望三连支持一下,感谢!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com