scroll-view俩栏滚动,点击左侧,右侧不会滚动到顶部问题

在Vue.js项目中遇到一个scroll-view组件的问题,当左侧栏被点击时,右侧栏未能自动滚动到顶部。通过在data中定义scrollTop变量并设置为0,然后在左侧scroll-view的点击事件中动态更新scrollTop的值,实现点击时切换右侧滚动状态。这种方法巧妙地利用了 Vue 的数据绑定和条件判断,有效地解决了这一交互难题。

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

在data添加scrollTop:0,并在标签内添加动态绑定属性 :scrollTop,为左侧scroll-view 绑定点击事件,并添加语句如下: this.scrollTop = this.scrollTop === 0 ? 1 : 0

<scroll-view class="right-scroll-view" scroll-y="true" style="height: 300px;" :style="{height: wh + 'px'}" :scroll-top="scrollTop">

data() {
  return {
     wh: 0,
     scrollTop: 0
   };
 }

onLoad() {
	const sysInfo = uni.getSystemInfoSync()
	this.wh = sysInfo.windowHeight // 屏幕可用高度
},


 activeChange() {
   this.scrollTop = this.scrollTop === 0 ? 1 : 0
 },
### 实现 scroll-view 切换时列表自动滚动顶部 在 UniApp 的开发中,`<scroll-view>` 是一个非常常用的组件,用于实现页面内的局部滚动效果。当需要切换 `<scroll-view>` 并使其内部的列表(list)自动滚动顶部时,可以通过设置 `scrollTop` 属性来控制滚动位置。 以下是具体的解决方案: #### 方法描述 通过绑定 `ref` 或者动态修改 `scrollTop` 值的方式可以实现这一功能。具体来说,在每次切换时调用 `this.$refs.scrollView.scrollTo(0)` 或直接更新 `scrollTop=0` 即可完成操作[^1]。 #### 示例代码 ```vue <template> <view> <!-- 左侧导航 --> <scroll-view class="leftScroll" :scroll-y="true" :style="{ height: windowHeight + 'px' }"> <view v-for="(category, index) in categories" :key="index" @click="switchCategory(index)"> {{ category.name }} </view> </scroll-view> <!-- 右侧内容区域 --> <scroll-view ref="rightScrollView" class="rightScroll" :scroll-y="true" :style="{ height: windowHeight + 'px' }" :scroll-top="scrollTop"> <view v-for="(item, index) in currentItems" :key="index" class="item"> {{ item.title }} </view> </scroll-view> </view> </template> <script> export default { data() { return { scrollTop: 0, windowHeight: 700, categories: [ { name: "类别一", items: [{ title: "项目A" }, { title: "项目B" }] }, { name: "类别二", items: [{ title: "项目C" }, { title: "项目D" }] } ], currentIndex: 0 }; }, computed: { currentItems() { return this.categories[this.currentIndex]?.items || []; } }, methods: { switchCategory(index) { this.scrollTop = 0; this.currentIndex = index; // 如果需要强制刷新视图,也可以尝试如下方法: this.$nextTick(() => { const scrollViewRef = this.$refs.rightScrollView; if (scrollViewRef && typeof scrollViewRef.scrollTo === "function") { scrollViewRef.scrollTo({ top: 0 }); } }); } } }; </script> <style scoped> .leftScroll { width: 20%; } .rightScroll { width: 80%; } .item { padding: 10px; border-bottom: 1px solid #ccc; } </style> ``` 上述代码展示了如何利用 Vue.js 数据驱动特性以及 `scrollTop` 动态调整右侧 `<scroll-view>` 的滚动条位置。每当左侧菜单被点击时,会重置 `scrollTop` 参数并重新计算当前显示的内容项[^2]。 #### 注意事项 - 需要确保 `scroll-view` 组件的高度固定或者能够自适应屏幕高度。 - 使用 `$refs` 调用原生 API (`scrollTo`) 来更精确地控制滚动行为可能更加可靠。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值