关于uni-app的scroll-view里的内容不更新问题

当scroll-view内的第一行直接使用v-for进行循环渲染时,可能出现列表数据更新但页面不更新的状况。为解决此问题,可以将v-for嵌套在scroll-view外的view标签内,即在scroll-view中先有一个view容器,然后在这个容器中使用v-for,这样可以确保列表数据变化时页面正确刷新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不更新的情况:scroll-view标签下的第一行直接是用v-for循环渲染。初次渲染是没有问题的,列表数据更新时页面不更新。

<scroll-view>
	<view v-for="item in list">{{item}}<view/>
<scroll-view/>

解决方法:scroll-view标签下的第一行不要直接用v-for,先套一个view,再在套的view里用v-for即可解决。

<scroll-view>
	<view>
		<view v-for="item in list">{{item}}<view/>
	</view>
<scroll-view/>
### 实现 uni-appscroll-view 组件的无缝循环滚动 为了实现在 `uni-app` 的 `scroll-view` 组件中的无缝循环滚动效果,可以采用设置定时器来自动触发滚动位置的变化,并通过监听滚动事件调整显示内容。需要注意的是,在实现过程中应避免使用带有 `fixed` 属性的元素以防止视图随页面滚动而移动[^1]。 下面是一个简单的例子展示如何创建一个水平方向上的无限轮播: ```html <template> <view class="container"> <!-- 设置横向滚动 --> <scroll-view class="scroll-view_H" :scroll-x="true" @scroll="handleScroll" :scroll-left="scrollLeft" ref="scrollViewRef" > <block v-for="(item, index) in items.concat(items)" :key="index"> <view class="scroll-item">{{ item }}</view> </block> </scroll-view> </view> </template> <script> export default { data() { return { items: ['Item 1', 'Item 2', 'Item 3'], // 原始数据项 currentIndex: 0, timer: null, scrollLeft: 0 }; }, mounted() { this.startAutoScroll(); }, methods: { handleScroll(e) { const { detail } = e; let width = Math.round(detail.scrollWidth / (this.items.length * 2)); if ((detail.scrollLeft >= width && !this.isAnimating)) { this.currentIndex++; this.scrollToNext(); } }, scrollToNext() { this.$nextTick(() => { this.scrollLeft += this.$refs.scrollViewRef.offsetWidth; // 更新滚动距离 setTimeout(() => { this.resetPosition(); // 调整回初始状态 }, 50); }); }, resetPosition() { this.scrollLeft -= this.$refs.scrollViewRef.offsetWidth; this.currentIndex %= this.items.length; if (this.timer !== null) clearTimeout(this.timer); this.startAutoScroll(); }, startAutoScroll() { this.timer = setInterval(() => { this.scrollToNext(); }, 3000); // 自动切换时间间隔 } }, beforeDestroy() { clearInterval(this.timer); } }; </script> <style scoped> .container { position: relative; } .scroll-view_H { white-space: nowrap; overflow: hidden; height: 80px; } .scroll-item { display: inline-block; min-width: 100%; text-align: center; line-height: 80px; font-size: 36rpx; } </style> ``` 此代码片段展示了如何利用 Vue.js 和 CSS 来构建一个基本的水平无限轮播功能。这的关键在于将原始列表重复一次并连接起来形成一个新的数组用于渲染,这样当到达最后一个项目时就可以平滑过渡到第一个项目上从而达到视觉上的连续性。同时设置了定时器每隔一段时间调用方法使容器向右滚动一定宽度的距离模拟自动播放的效果;并且在每次完成一轮完整的动画之后重置当前位置以便继续下一个周期的播放。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值