uniapp如何将底部导航组件化
组件化底部导航的实现方法
在Uniapp中,将底部导航组件化可以提高代码复用性和可维护性。以下是具体实现步骤:
创建自定义导航组件
在components目录下新建tab-bar.vue文件,定义导航结构和样式:
<template>
<view class="tab-bar">
<view
v-for="(item, index) in list"
:key="index"
@click="switchTab(item)"
class="tab-item"
>
<image :src="current === item.pagePath ? item.selectedIconPath : item.iconPath"/>
<text :class="{active: current === item.pagePath}">{{item.text}}</text>
</view>
</view>
</template>
<script>
export default {
props: {
current: String,
list: Array
},
methods: {
switchTab(item) {
if (this.current !== item.pagePath) {
uni.switchTab({
url: item.pagePath
})
}
}
}
}
</script>
<style>
.tab-bar {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
background: #fff;
box-shadow: 0 -1px 1px rgba(0,0,0,0.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 5px 0;
}
.tab-item image {
width: 24px;
height: 24px;
}
.active {
color: #007AFF;
}
</style>
配置导航数据
在项目根目录或公共文件夹中创建tabBar.js配置文件:
export default [
{
"pagePath": "/pages/home/home",
"iconPath": "/static/tabbar/home.png",
"selectedIconPath": "/static/tabbar/home-active.png",
"text": "首页"
},
{
"pagePath": "/pages/category/category",
"iconPath": "/static/tabbar/category.png",
"selectedIconPath": "/static/tabbar/category-active.png",
"text": "分类"
},
{
"pagePath": "/pages/cart/cart",
"iconPath": "/static/tabbar/cart.png",
"selectedIconPath": "/static/tabbar/cart-active.png",
"text": "购物车"
},
{
"pagePath": "/pages/user/user",
"iconPath": "/static/tabbar/user.png",
"selectedIconPath": "/static/tabbar/user-active.png",
"text": "我的"
}
]
在页面中使用组件 在需要显示底部导航的页面中引入组件:
<template>
<view>
<!-- 页面内容 -->
<tab-bar :current="currentPage" :list="tabList"/>
</view>
</template>
<script>
import tabBar from '@/components/tab-bar.vue'
import tabList from '@/config/tabBar.js'
export default {
components: { tabBar },
data() {
return {
currentPage: '/pages/home/home',
tabList: tabList
}
}
}
</script>
注意事项
-
确保导航图片资源路径正确,建议使用绝对路径
-
每个tab页面的json配置中需要禁用原生导航:
{ "navigationStyle": "custom" } -
组件样式需要根据实际项目调整z-index值,避免被其他元素覆盖
-
对于非tabbar页面,可以通过隐藏组件或使用条件渲染控制显示
进阶优化
添加徽标功能可以在组件中扩展:
<view class="tab-item">
<image :src="current === item.pagePath ? item.selectedIconPath : item.iconPath"/>
<text :class="{active: current === item.pagePath}">{{item.text}}</text>
<view v-if="item.badge" class="badge">{{item.badge}}</view>
</view>
样式部分新增:
.badge {
position: absolute;
top: 0;
right: 20%;
background: #f00;
color: #fff;
border-radius: 10px;
min-width: 16px;
height: 16px;
font-size: 12px;
text-align: center;
line-height: 16px;
padding: 0 3px;
}






