uniapp滚动组件
uniapp 滚动组件实现方法
scroll-view 基础用法
uniapp 提供了 scroll-view 组件实现滚动区域。横向滚动需要设置 scroll-x 属性,纵向滚动需要设置 scroll-y 属性。
<scroll-view scroll-y style="height: 300px;">
<view v-for="item in 50" :key="item">列表项 {{item}}</view>
</scroll-view>
滚动事件监听
通过 @scroll 事件可以监听滚动位置,获取滚动距离。
<scroll-view
scroll-y
style="height: 300px;"
@scroll="handleScroll"
>
<!-- 内容 -->
</scroll-view>
methods: {
handleScroll(e) {
console.log('滚动距离', e.detail.scrollTop)
}
}
滚动到指定位置
使用 scroll-into-view 属性可以滚动到指定子元素位置。
<scroll-view
scroll-y
style="height: 300px;"
:scroll-into-view="toView"
>
<view id="item1">项目1</view>
<view id="item30">项目30</view>
</scroll-view>
<button @click="toView = 'item30'">滚动到项目30</button>
data() {
return {
toView: ''
}
}
上拉加载更多
结合 @scrolltolower 事件可以实现上拉加载功能。
<scroll-view
scroll-y
style="height: 300px;"
@scrolltolower="loadMore"
>
<!-- 列表内容 -->
<view class="loading">加载中...</view>
</scroll-view>
下拉刷新
使用 refresher-enabled 开启下拉刷新功能。
<scroll-view
scroll-y
style="height: 300px;"
refresher-enabled
:refresher-triggered="refreshing"
@refresherrefresh="onRefresh"
>
<!-- 内容 -->
</scroll-view>
data() {
return {
refreshing: false
}
},
methods: {
onRefresh() {
this.refreshing = true
setTimeout(() => {
this.refreshing = false
}, 1000)
}
}
性能优化建议
对于长列表场景,建议配合 uvue 的 recycle-list 组件使用,减少内存占用。
<recycle-list
for="item in longList"
scroll-y
style="height: 100vh;"
>
<cell-slot>
<view>{{item.text}}</view>
</cell-slot>
</recycle-list>






