微信小程序中实现 Tab 切换效果是一个常见的需求,通常用于实现多页面切换或内容分类展示。
首页 分类 我的 首页内容 分类内容 我的内容
/* 容器样式 */ .tab-container { display: flex; flex-direction: column; height: 100vh; } /* Tab 栏样式 */ .tab-bar { display: flex; justify-content: space-around; background-color: #f8f8f8; padding: 10px 0; } /* Tab 项样式 */ .tab-item { padding: 10px 20px; font-size: 16px; color: #333; cursor: pointer; } /* 选中 Tab 项样式 */ .tab-item.active { color: #07c160; border-bottom: 2px solid #07c160; } /* 内容区域样式 */ .content { flex: 1; padding: 20px; background-color: #fff; }
Page({ data: { activeTab: 0, // 当前选中的 Tab 索引 }, // 切换 Tab switchTab(event) { const index = event.currentTarget.dataset.index; // 获取点击的 Tab 索引 this.setData({ activeTab: index, // 更新选中的 Tab }); }, });
如果需要支持左右滑动切换 Tab,可以使用 swiper
组件:
首页内容 分类内容 我的内容
在 JS 中监听 swiper
的切换事件:
Page({ data: { activeTab: 0, }, // 滑动切换 swiperChange(event) { const index = event.detail.current; this.setData({ activeTab: index, }); }, // 点击 Tab 切换 switchTab(event) { const index = event.currentTarget.dataset.index; this.setData({ activeTab: index, }); }, });
如果需要动态生成 Tab,可以在 JS 中定义 Tab 数据:
Page({ data: { tabs: ['首页', '分类', '我的'], // Tab 名称 activeTab: 0, }, switchTab(event) { const index = event.currentTarget.dataset.index; this.setData({ activeTab: index, }); }, });
在 WXML 中使用 wx:for
动态渲染 Tab:
{{item}}
可以为 Tab 切换添加动画效果,例如使用 wx.createAnimation
:
Page({ data: { activeTab: 0, animationData: {}, }, onLoad() { this.animation = wx.createAnimation({ duration: 300, timingFunction: 'ease', }); }, switchTab(event) { const index = event.currentTarget.dataset.index; this.setData({ activeTab: index, }); // 执行动画 this.animation.translateX(index * 100).step(); this.setData({ animationData: this.animation.export(), }); }, });
在 WXML 中应用动画:
首页内容 分类内容 我的内容