项目中新建一个 components文件夹;鼠标选中components文件夹右键选择新建component,输入Tabs组件名会自动生成Tabs.js\Tabs.json\Tabs.wxml\Tabs.wxss文件。
组件Tabs文件夹如下:
Tabs.wxml //文件
<!-- 导航 -->
<view class="tabbar">
<view wx:for="{{tabList}}" wx:key="{{index}}" bindtap="switchTab" data-index="{{index}}" class="tab-item {{currentTab === index ? 'active' : ''}}">
{{item}}
</view>
</view>
<!-- 导航内容 -->
<view class="content">
<view wx:for="{{tabContentList}}" wx:key="{{index}}" wx:if="{{currentTab === index}}" class="tab-content">
{{item}}
</view>
</view>
Tabs.js //文件
Component({
// 组件的属性列表
properties: {
},
// 组件的初始数据
data: {
currentTab: 0,
tabList: ['Tab1', 'Tab2', 'Tab3','Tab4', 'Tab5'],
tabContentList: ['Tab 1 Content', 'Tab 2 Content', 'Tab 3 Content','Tab 4 Content', 'Tab 5 Content'],
},
// 组件的方法列表
methods: {
switchTab(event) {
const index = event.currentTarget.dataset.index;
this.setData({
currentTab: index,
});
},
}
})
Tabs.wxss //文件
.tabbar {
display: flex;
justify-content: space-around;
align-items: center;
background-color: #fff;
box-shadow: 0px -2px 4px rgba(0, 0, 0, 0.1);
padding-bottom: 10px;
}
.tab-item {
font-size: 16px;
color: #333;
cursor: pointer;
border-bottom: 2px solid transparent;
padding-bottom: 4px;
}
.tab-item.active {
color: #ff0000;
border-bottom-color: #ff0000;
background-color: transparent; /* 将背景色设置为透明 */
}
.content {
margin-top: 20px;
text-align: center;
font-size: 18px;
}
.tab-content {
padding: 20px;
}
Tabs.json //文件
{
"component": true,
"usingComponents": {}
}
页面demo文件夹如下:
demo.wxml //文件
<Tabs>
<view>
<tabbar></tabbar>
</view>
</Tabs>
demo.json //文件
{
"navigationBarTextStyle": "white",
"navigationBarBackgroundColor": "#005e29",
"usingComponents": {
"Tabs":"/components/Tabs/Tabs" //引入组件
}
}