uniapp如何将底部导航组件化
组件化底部导航的实现方法
在Uniapp中实现底部导航组件化,可以通过自定义组件的方式完成。以下是具体实现步骤:
创建自定义导航组件
新建一个组件文件如/components/tab-bar/tab-bar.vue,结构如下:
<template>
<view class="tab-bar">
<view
v-for="(item, index) in list"
:key="index"
class="tab-item"
@click="switchTab(item)">
<image :src="selected === item.pagePath ? item.selectedIconPath : item.iconPath" />
<text :class="{active: selected === item.pagePath}">{{item.text}}</text>
</view>
</view>
</template>
<script>
export default {
props: {
selected: {
type: String,
default: ''
}
},
data() {
return {
list: [
{
pagePath: "/pages/index/index",
iconPath: "/static/tabbar/home.png",
selectedIconPath: "/static/tabbar/home-active.png",
text: "首页"
},
{
pagePath: "/pages/user/user",
iconPath: "/static/tabbar/user.png",
selectedIconPath: "/static/tabbar/user-active.png",
text: "我的"
}
]
}
},
methods: {
switchTab(item) {
uni.switchTab({
url: item.pagePath
})
}
}
}
</script>
<style>
.tab-bar {
position: fixed;
bottom: 0;
width: 100%;
display: flex;
background: #fff;
box-shadow: 0 -1px 6px rgba(0,0,0,.1);
}
.tab-item {
flex: 1;
text-align: center;
padding: 8px 0;
}
.tab-item image {
width: 24px;
height: 24px;
}
.tab-item text {
display: block;
font-size: 12px;
color: #999;
}
.tab-item text.active {
color: #007AFF;
}
</style>
在页面中使用组件 在需要显示底部导航的页面中引入组件:
<template>
<view>
<!-- 页面内容 -->
<tab-bar :selected="currentPage"></tab-bar>
</view>
</template>
<script>
import tabBar from '@/components/tab-bar/tab-bar.vue'
export default {
components: { tabBar },
data() {
return {
currentPage: '/pages/index/index'
}
}
}
</script>
动态路由匹配方案
对于需要根据当前路由自动高亮导航项的情况,可以通过监听路由变化实现:
onShow() {
const pages = getCurrentPages()
this.currentPage = '/' + pages[pages.length - 1].route
}
全局注册方案
如需在所有页面使用,可以在main.js中全局注册组件:
import tabBar from '@/components/tab-bar/tab-bar.vue'
Vue.component('tab-bar', tabBar)
注意事项
底部导航组件需要使用position: fixed定位固定在底部。页面内容区域需要预留底部导航的高度,防止内容被遮挡。
在pages.json中需要配置tabBar的页面为"style": { "navigationBarTitleText": "..." },避免原生导航栏与自定义导航栏冲突。

组件中的路由跳转应使用uni.switchTab方法,确保正确切换到tabbar页面。






