uniapp tab选项卡
时间: 2025-03-26 21:25:01 浏览: 53
### 创建和使用 Tab 选项卡组件
在 UniApp 中创建和使用 Tab 选项卡组件可以通过多种方式实现。下面提供一种基于 `swiper` 和 `tabs` 组件的方式,这种方式能够很好地适配不同平台并提供良好的用户体验。
#### HTML 结构
首先,在页面模板文件中定义基本结构:
```html
<template>
<view class="container">
<!-- Tabs 导航 -->
<scroll-view scroll-x class="tab-bar" :class="{ 'fixed': isFixed }">
<block v-for="(item, index) in tabList" :key="index">
<view
@tap="handleClick(item.navTarget)"
:id="'tab-' + item.text"
:class="[activeNav === item.navTarget ? 'active' : '', 'tab-item']"
>
{{ item.text }}
</view>
</block>
</scroll-view>
<!-- Swiper 内容区 -->
<swiper
:current="currentIndex"
duration="300"
bindchange="onChangeItem"
style="height: calc(100vh - 80rpx);"
>
<swiper-item v-for="(item, idx) in contentList" :key="idx">
<view :id="item.id">{{ item.content }}</view>
</swiper-item>
</swiper>
</view>
</template>
```
此部分HTML代码构建了一个包含水平滚动视图作为标签栏以及用于展示各页内容的 swiper 控件布局[^2]。
#### JavaScript 部分
接着是在脚本里处理逻辑交互的部分:
```javascript
<script>
export default {
data() {
return {
currentIndex: 0,
activeNav: '',
isFixed: false,
tabList: [
{ text: "首页", navTarget: "#home" },
{ text: "分类", navTarget: "#category" },
{ text: "购物车", navTarget: "#cart" }
],
contentList: [
{ id: '#home', content: '这是首页的内容...' },
{ id: '#category', content: '这里是分类详情...' },
{ id: '#cart', content: '查看我的购物车...' }
]
};
},
methods: {
handleClick(navTarget) {
this.activeNav = navTarget;
uni.pageScrollTo({
selector: `${this.activeNav}`,
duration: 300
});
},
onChangeItem(e) {
const newIndex = e.detail.current;
this.currentIndex = newIndex;
this.activeNav = this.tabList[newIndex].navTarget;
setTimeout(() => {
uni.pageScrollTo({
selector: `${this.activeNav}`,
duration: 300
});
}, 50);
}
},
onPageScroll(res) {
let scrollTop = res.scrollTop;
if (scrollTop >= 80 && !this.isFixed || scrollTop < 80 && this.isFixed){
this.isFixed = !this.isFixed;
}
}
};
</script>
```
这段JavaScript代码负责管理当前激活状态、响应用户的点击事件来切换页面,并通过监听页面滚动调整固定头部的状态[^3]。
#### CSS 样式
最后是样式表中的配置,用来美化界面元素:
```css
<style scoped lang="scss">
.container {
padding-top: 80rpx; /* 设置顶部内边距 */
}
.tab-bar {
position: relative;
white-space: nowrap;
background-color: #fff;
z-index: 999;
&.fixed{
position: fixed;
top: var(--status-bar-height);
width: 100%;
}
.tab-item {
display: inline-block;
height: 80rpx;
line-height: 80rpx;
margin-right: 40rpx;
&:last-child {
margin-right: 0;
}
&.active {
color: blue;
font-weight: bold;
}
}
}
</style>
```
上述CSS规则设置了 `.tab-bar` 类及其子项的基础外观属性,同时也包含了针对`.fixed`类别的特殊样式以适应吸顶效果的需求[^4]。
阅读全文
相关推荐















