uniapp scroll-view无感加载数据,保持滚动位置不变 - 优化用户体验
{"title":"js uniapp的scroll-view如果数组改变,比如数组拼接了新的一段数据,结果scroll-view一下跳转到顶部了,那怎么让用户无感加载数据呢,就是想让scroll-view停留的位置不变,但是又加载了新数据在里面","description":"本文介绍了如何在uniapp的scroll-view组件中实现无感加载数据,即使数组拼接了新数据,也能保持滚动位置不变,从而提供更流畅的用户体验。","keywords":"uniapp, scroll-view, 无感加载, 滚动位置, scroll-into-view, scroll-top, 数据加载, 用户体验","content":"要实现无感加载数据,可以使用scroll-view的scroll-into-view属性和scroll-top属性配合使用。\n\n1. 在data中定义scroll-view的id和scrollTop属性:\n\njavascript\ndata() {\n return {\n scrollViewId: 'scroll-view',\n scrollTop: 0,\n dataList: [] // 数据数组\n }\n}\n\n\n2. 在scroll-view组件上绑定id和scroll事件:\n\nhtml\n<scroll-view :id="scrollViewId" :scroll-top="scrollTop" @scroll="onScroll">\n <!-- 数据列表 -->\n <view v-for="(item, index) in dataList" :key="index">{{ item }}</view>\n</scroll-view>\n\n\n3. 在获取到新数据后,将新数据拼接到原有的数据数组上,并通过setData更新数据:\n\njavascript\n// 获取新数据\nconst newDataList = await fetchData();\n\n// 拼接新数据\nthis.dataList = this.dataList.concat(newDataList);\n\n// 更新scroll-view的scrollTop,以保持停留位置不变\nconst query = uni.createSelectorQuery();\nquery.select('#' + this.scrollViewId).boundingClientRect();\nquery.selectViewport().scrollOffset();\nquery.exec((res) => {\n const scrollViewHeight = res[0].height; // scroll-view的可视高度\n const scrollHeight = res[1].scrollHeight; // scroll-view的内容高度\n const scrollTop = res[1].scrollTop; // scroll-view的滚动位置\n\n if (scrollHeight - scrollViewHeight - scrollTop <= 10) {\n // 如果滚动位置接近底部,则将scrollTop设置为scrollHeight - scrollViewHeight,保持停留在底部\n this.scrollTop = scrollHeight - scrollViewHeight;\n } else {\n // 否则将scrollTop设置为原来的位置,保持停留在原位置\n this.scrollTop = scrollTop;\n }\n});\n\n\n4. 定义onScroll方法,用于监听页面滚动事件:\n\njavascript\nonScroll(e) {\n const { scrollTop } = e.detail;\n this.scrollTop = scrollTop;\n},\n\n\n这样,当数组改变时,scroll-view会保持停留在原位置,同时又加载了新数据在其中。"}
原文地址: https://www.cveoy.top/t/topic/pTK3 著作权归作者所有。请勿转载和采集!