先上图
录制软件问题导致滑动过程中侧边有白边,实际模拟器和手机测试正常
因为在写项目的过程中需要写一个tab滑动切换的界面,微信小程序没有提供,所以就自己用swiper实现一个
主要是使用了swiper内的current属性以及组件通信的连接
代码
wxml:
<!-- Tab部分 -->
<tab-control class="tabcontrolclass"
id="TestTabComponent"
bind:sendIndex="getTabIndex"
titles="{
{['Tab1','Tab2','Tab3','Tab4']}}"></tab-control>
<!-- 内容部分 -->
<swiper class="TestTabBody"
current="{
{swipercurrent}}"
bindchange="swipercurrentchange"
circular="{
{true}}">
<swiper-item class="TestTabBody-item" item-id="">
<!-- swiper-item -->
<view>我是内容1</view>
</swiper-item>
<swiper-item class="TestTabBody-item" item-id="">
<!-- swiper-item -->
<view>我是内容2</view>
</swiper-item>
<swiper-item class="TestTabBody-item" item-id="">
<!-- swiper-item -->
<view>我是内容3</view>
</swiper-item>
<swiper-item class="TestTabBody-item" item-id="">
<!-- swiper-item -->
<view>我是内容4</view>
</swiper-item>
</swiper>
wxss:
.TestTabBody {
height: 1000rpx;
background: #eee;
}
.TestTabBody-item {
height: 400rpx;
background: #34ace0;
margin-top: 10rpx;
color: #fff;
}
.tabcontrolclass {
border-bottom: 2rpx solid rgb(233, 229, 229);
}
使用组件页面的js:
Page({
data: {
swipercurrent: 0
},
//获取当前tab的current值赋值给swiper的current
getTabIndex(e) {
this.setData({
swipercurrent: e.detail.TabcurrentIndex
})
},
//滑动内容,设置Tab跟着一起变化
swipercurrentchange(e) {
const tabcontrol = this.selectComponent('#TestTabComponent')
tabcontrol.setData({
currentIndex: e.detail.current
})
}
})
组件wxml:
<view class="TestTabbar">
<block wx:for="{
{titles}}" wx:key="index">
<!-- 获取tab点击的index然后设置一个currentIndex来控制点击的样式 -->
<view class="TestTabbar-item yahei-font {
{currentIndex==index?'TestTabbarActive':''}}"
bind:tap="handleClickTab"
data-index="{
{index}}">
<text class="TestTabbarText">{
{
item}}</text>
</view>
</block>
</view>
组件wxss:
.TestTabbar {
display: flex;
height: 60rpx;
padding: 16rpx 0;
border-bottom: 2rpx solid #BDBDBD;
}
.TestTabbar-item {
flex: 1;
text-align: center;
line-height: 60rpx;
font-weight: 550;
color: #aaa69d;
}
.TestTabbarActive {
color: #34ace0;
}
.TestTabbarActive text {
border-bottom: #34ace0 solid 6rpx;
padding: 18rpx 1rpx;
}
组件js:
// Components/tab-contorl/tab-control.js
Component({
properties: {
titles: {
type: Array
}
},
data: {
currentIndex: 0
},
methods: {
handleClickTab(e) {
//拿到点击的index
const index = e.currentTarget.dataset.index
this.setData({
currentIndex: index
})
//给页面传递目前点击的tab
this.triggerEvent('sendIndex', {
TabcurrentIndex: index })
}
}
})
这样就可以实现一个简单的滑动tab