小程序scroll,swiper使用详解

本文详细解析了如何在uni-app中结合scroll和swiper组件,实现水平滚动及内容切换的效果。在实践中,遇到的关键点包括为scroll-view设置white-space: nowrap以保证内容横向布局,以及为scroll内部子元素设定display: inline-block和指定高度,以确保滑动功能正常运行。

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

下面代码是结合scroll和swiper组合使用,实现tab和内容的切换,

scroll是横向滚动,

<template>
  <view class="content">
    <view>
      <scroll-view
        class="scroll-view_H"
        scroll-x="true"
        @scroll="scroll"
        scroll-left="120"
      >
        <view
          id="demo1"
          class="scroll-view-item_H uni-bg-red"
          v-for="(item, index) in tab"
          :key="index"
          @click="scroll(index)"
          ><view :class="tabIndex == index ? 'active' : ''">
            {{ item }}
          </view></view
        >
      </scroll-view>
      <swiper  @change="handle_swiperChange"   :current="tabIndex" next-margin="100rpx">
        <swiper-item
         
        
          class="swiper"
          v-for="(item, index) in tab"
          :key="index"
          
        >
          {{ item }}
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>
 
<script>
export default {
  data() {
    return {
      tabIndex: 0,
      tab: ["热搜榜", "视频榜", "博客榜"],
    };
  },
  methods: {
    scroll(i) {
      this.tabIndex = i;
    },
    handle_swiperChange(e) {
      console.log(e);
	  this.tabIndex=e.detail.current
    },
  },
};
</script>
 
<style scoped lang='less'>
.content {
  height: 100vw;
  .scroll-view_H {
    white-space: nowrap;
  }
  .uni-bg-red {
    height: 50rpx;
    display: inline-block;
    margin-right: 30rpx;
  }
  .uni-bg-green {
    height: 50rpx;
    display: inline-block;
    margin-right: 30rpx;
  }
  .uni-bg-blue {
    height: 50rpx;
    display: inline-block;
  }
}
.swiper {
  width: 90rpx;
}
.active {
  color: red;
}
</style>

然后是使用中遇到的坑:

1.首先需要给scroll-view 设置  white-space: nowrap;

2.需要给scroll内的子元素添加: display: inline-block;height:高度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值