Uniapp中动态控制scroll-view滚动的方式
在Uniapp 4.45中,动态修改scroll-view的scroll-left属性时无法触发滚动(直接设置scroll-left属性值没问题),这通常是因为数据更新与 DOM 渲染之间的异步特性导致的。知道了原因,但是直接修改scroll-left属性值还是失败,尝试了很多方案,最后结合Vue v-if指令成功。
完整代码:
<template><view class="container"><!-- 横向滚动容器 --><scroll-view scroll-x :scroll-left="scrollLeft" :scroll-with-animation="true" class="scroll-box" @scroll="handleScroll"v-if="scrollViewVisible"><view v-for="item in itemList" :key="item.id" class="scroll-item">元素 {{ item.id }}</view></scroll-view><!-- 控制按钮 --><button @click="scrollToLeft">滚动到最左侧</button></view>
</template><script setup>import {ref,nextTick} from 'vue';// 响应式数据let scrollViewVisible = ref(true);const scrollLeft = ref(0); // 控制横向滚动位置const itemList = ref(Array.from({length: 20}, (_, i) => ({id: i + 1})));// 滚动事件监听const handleScroll = (e) => {console.log('当前横向滚动位置:', e.detail.scrollLeft);};// 滚动到最左侧方法const scrollToLeft = () => {scrollViewVisible.value = false;nextTick(() => {scrollViewVisible.value = true;scrollLeft.value = 0; // 将滚动位置重置为0(最左侧)})};
</script><style scoped>/* 容器样式 */.container {padding: 20rpx;}/* 关键:必须设置固定宽度且允许横向滚动 */.scroll-box {width: 100%;height: 200rpx;white-space: nowrap;/* 禁止换行 */border: 1px solid #eee;}/* 横向排列的子元素 */.scroll-item {display: inline-block;width: 150rpx;height: 180rpx;line-height: 180rpx;text-align: center;background-color: #f0f0f0;margin-right: 20rpx;}
</style>