【微信小程序】左右滑动切换标签页
在开发微信小程序时,经常会遇到需要实现左右滑动切换标签页(Tab)的场景,以提升用户体验和界面的交互性。微信小程序自身提供了一些组件和API来帮助我们实现这样的功能,但直接的左右滑动切换标签页并不是通过单个组件直接完成的,而是需要结合使用swiper组件和自定义的Tab导航来实现。下面,我将详细介绍如何在小程序中实现这一功能。
页面结构
wxml
- 滑动页面使用swiper组件实现
- 滚动区域使用scroll-view组件实现
<!--pages/side/side.wxml-->
<navigation-bar title="滑动切换标签页" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<!-- pages/index/index.wxml -->
<view class="container">
<!-- 自定义Tab导航 -->
<view class="tabs">
<block wx:for="{{tabs}}" wx:key="index" wx:for-item="tab">
<view
bindtap="switchTab"
data-index="{{index}}"
class="tab-item {{currentTab === index ? 'active' : ''}}"
bindtap="switchTab"
data-index="{{index}}"
>
{{tab.title}}
</view>
</block>
</view>
<!-- swiper组件实现滑动 -->
<swiper
bindchange="swiperChange"
current="{{currentTab}}"
circular
>
<block wx:for="{{tabs}}" wx:key="index">
<swiper-item>
<!-- 这里放置每个Tab对应的内容 -->
<view class="swiper-content">
{{item.content}}
</view>
<scroll-view scroll-y style="height: 100%;">
<view class="list-item" wx:for="{{item.datalist}}" wx:for-item="content">{{content}}</view>
<view class="list-item"></view>
</scroll-view>
</swiper-item>
</block>
</swiper>
</view>
wxss
- 将page高度设置为100vh
- 设置 page 为 flex布局,这样 container 设置
height:100%
时就会占满页面的剩余高度 - 列表的最后一项加个 padding 用于将内容抬高到底部的 tab 栏上面
/* pages/side/side.wxss */
page {
display: flex;
flex-direction: column;
height: 100vh;
box-sizing: border-box;
}
.container {
box-sizing: border-box;
height: 100%;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
}
.tabs {
display: flex;
justify-content: space-around;
width: 100%;
margin-bottom: 10px;
}
.tab-item {
padding: 10px 20px;
border-bottom: 2px solid transparent;
}
.tab-item.active {
border-bottom-color: #007aff;
color: #007aff;
}
.swiper-content {
/* 内容样式,根据需要自定义 */
text-align: center;
padding: 20px;
background-color: #eee;
}
swiper {
height: 100%;
width: 100%;
}
.list-item {
padding: 20px;
border: 1px solid black;
}
.list-item:last-child{
padding-bottom: 100rpx;
}
typescript
// pages/index/index.js
interface Tab{
title: String,
content: String,
datalist: Array<string>
}
Page({
data: {
// 初始化Tab数据
tabs: [
{
title: 'Tab 1',
content: '这是Tab 1的内容',
datalist: []
},
{
title: 'Tab 2',
content: '这是Tab 2的内容',
datalist: []
},
{
title: 'Tab 3',
content: '这是Tab 3的内容',
datalist: []
}
] as Tab[],
currentTab: 0,
},
// 切换Tab
switchTab: function (e: any) {
const index = e.currentTarget.dataset.index;
this.setData({
currentTab: index
});
},
// swiper组件的滑动改变事件
swiperChange: function (e: any) {
const { current } = e.detail;
this.setData({
currentTab: current
});
},
onLoad: function (){
this.data.tabs.forEach(e => {
let total = Math.ceil(Math.random() * 20 + 20);
for(let i = 0; i < total; ++i) {
e.datalist.push('data: ' + String(i))
}
e.content = `共${e.datalist.length}条数据`
})
this.setData({tabs: this.data.tabs})
}
})
总结
通过以上步骤,我们可以在微信小程序中实现一个基本的左右切换标签页的功能。这里的关键是结合使用swiper组件和自定义的Tab导航,并通过事件处理来同步两者的状态。此外,根据实际需求,你还可以添加更多的功能,比如动态加载Tab内容、滑动动画效果