微信小程序之Tabs组件

知识点: 父向子传传值 子向父传值 样式激活
样式代码如下:

<Tabs tabs="{{tabs}}" currentIndex="{{currentIndex}}" bindchangeTabs='changeTabs'></Tabs>

// 父
Page({
  data: {
    tabs: [
      {
        id: 0,
        title: '全部'
      },{
        id: 1,
        title: '今日'
      },{
        id: 2,
        title: '昨日'
      },
    ],
    currentIndex: -1
  },
  changeTabs(e) {
    let {index} = e.detail
    this.setData({
      currentIndex: index
    })
  }
})
// 子组件
<view class="tabs">
  <view class="tabs_title">  
    <view  wx:for="{{tabs}}" wx:key="index" data-index="{{item.id}}" class="tabs_item {{currentIndex === item.id? 'active' : ''}}" bindtap="changeTabs">{{item.title}}</view>
  </view>
  <view class="tabs_content">
    <view hidden='{{currentIndex != 0}}'>页面1</view>
    <view hidden='{{currentIndex != 1}}'>页面2</view>
    <view hidden='{{currentIndex != 2}}'>页面3</view>
  </view>
</view>

// css
.tabs_title {
  display: flex;
  text-align: center;
  align-items: center;
}
.tabs_item {
  flex: 1;
  padding: 10rpx;
  border-bottom: 1px solid #fff;
}
.active {
  border-bottom: 1px solid brown;
}

// js
Component({
  properties: {
    tabs: {
      type: Array,
      value: []
    },
    currentIndex: {
      type: Number,
    },
  },
  methods: {
    changeTabs(e) {
      let { index } = e.currentTarget.dataset
      this.triggerEvent('changeTabs', {index})
    },
    
  }
})

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在微信小程序中实现选项卡(tabs)效果,可以使用小程序的 `scroll-view` 组件和 `swiper` 组件。 使用 `scroll-view` 组件可以实现横向滚动的效果,而 `swiper` 组件可以实现左右滑动的效果。可以将 `swiper` 组件放在 `scroll-view` 组件中,这样就可以实现选项卡的效果了。 具体实现步骤如下: 1. 在 `wxml` 文件中定义一个 `scroll-view` 组件,并设置 `scroll-x` 属性为 true,表示横向滚动。 ``` <scroll-view class="tab-bar" scroll-x="{{true}}"> <!-- 这里放置选项卡的内容 --> </scroll-view> ``` 2. 在 `scroll-view` 组件中放置 `swiper` 组件,设置 `current` 属性为当前选中的选项卡索引,可以通过 `bindchange` 事件获取用户点击的选项卡索引。 ``` <scroll-view class="tab-bar" scroll-x="{{true}}"> <swiper current="{{current}}" bindchange="swiperChange"> <swiper-item>选项卡1</swiper-item> <swiper-item>选项卡2</swiper-item> <swiper-item>选项卡3</swiper-item> </swiper> </scroll-view> ``` 3. 在 `js` 文件中定义 `swiperChange` 方法,获取用户点击的选项卡索引,并更新 `current` 变量的值,以便在页面中显示当前选中的选项卡。 ``` Page({ data: { current: 0, // 当前选中的选项卡索引 }, swiperChange: function(e) { // 获取用户点击的选项卡索引 var index = e.detail.current; // 更新当前选中的选项卡索引 this.setData({ current: index, }); }, }); ``` 4. 根据当前选中的选项卡索引,动态显示对应的内容。 ``` <swiper-item> <!-- 这里放置选项卡1的内容 --> </swiper-item> <swiper-item> <!-- 这里放置选项卡2的内容 --> </swiper-item> <swiper-item> <!-- 这里放置选项卡3的内容 --> </swiper-item> ``` 以上就是在微信小程序中实现选项卡效果的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值