UniApp 自定义 TabBar 实现指南 - 构建个性化的底部导航栏
在 UniApp 中,您可以通过 uni-app 自带的 tabBar 组件来实现底部导航栏的功能,也可以通过自定义组件来实现更加个性化的 tabBar。
以下是实现自定义 tabBar 的步骤:
-
创建一个自定义 tabBar 组件,可以在 pages 文件夹下新建一个 tabBar 文件夹,然后在该文件夹下新建一个 tabBar.vue 文件。
-
在 tabBar.vue 中,可以使用 uni-app 提供的 tabBar 组件作为容器,然后在其中自定义需要的 tabBar 样式和内容。
<template>
<view class="custom-tab-bar">
<view class="tab-item" :class="{active:activeIndex===0}" @click="handleClick(0)">
<text class="iconfont icon-home"></text>
<text class="title">首页</text>
</view>
<view class="tab-item" :class="{active:activeIndex===1}" @click="handleClick(1)">
<text class="iconfont icon-form"></text>
<text class="title">表单</text>
</view>
<view class="tab-item" :class="{active:activeIndex===2}" @click="handleClick(2)">
<text class="iconfont icon-user"></text>
<text class="title">我的</text>
</view>
</view>
</template>
- 在 tabBar.vue 中,可以使用 props 来接收父组件传递过来的参数,并且可以使用 $emit 来向父组件发送事件。
<script>
export default {
props: {
activeIndex: {
type: Number,
default: 0
}
},
methods: {
handleClick(index) {
this.$emit('changeTab', index)
}
}
}
</script>
- 在父组件中,可以使用自定义 tabBar 组件,并且通过 props 来传递参数和监听事件。
<template>
<view>
<view class="content">
<router-view></router-view>
</view>
<custom-tab-bar :activeIndex="activeIndex" @changeTab="handleChangeTab"></custom-tab-bar>
</view>
</template>
<script>
import CustomTabBar from '@/components/tabBar/tabBar.vue'
export default {
components: {
CustomTabBar
},
data() {
return {
activeIndex: 0
}
},
methods: {
handleChangeTab(index) {
this.activeIndex = index
}
}
}
</script>
- 在 App.vue 中,可以通过设置 tabBar 的 custom 属性来使用自定义 tabBar 组件。
<template>
<view>
<custom-tab-bar :activeIndex="activeIndex" @changeTab="handleChangeTab"></custom-tab-bar>
<router-view></router-view>
</view>
</template>
<script>
import CustomTabBar from '@/components/tabBar/tabBar.vue'
export default {
components: {
CustomTabBar
},
data() {
return {
activeIndex: 0
}
},
methods: {
handleChangeTab(index) {
this.activeIndex = index
}
},
tabBar: {
custom: true,
color: '#7A7E83',
selectedColor: '#007AFF',
backgroundColor: '#ffffff',
list: [
{
pagePath: '/pages/index/index',
text: '首页',
iconPath: '/static/tabBar/home.png',
selectedIconPath: '/static/tabBar/home-active.png'
},
{
pagePath: '/pages/form/form',
text: '表单',
iconPath: '/static/tabBar/form.png',
selectedIconPath: '/static/tabBar/form-active.png'
},
{
pagePath: '/pages/user/user',
text: '我的',
iconPath: '/static/tabBar/user.png',
selectedIconPath: '/static/tabBar/user-active.png'
}
]
}
}
</script>
以上就是实现自定义 tabBar 的步骤,您可以根据自己的需求修改 tabBar 样式和内容。
注意: 为了确保搜索引擎能够正确识别您的内容,请使用简洁、描述性的标题和描述,并使用相关的关键词。同时,将代码示例中的双引号替换为单引号,以便搜索引擎更好地理解代码结构。
原文地址: https://www.cveoy.top/t/topic/mLeZ 著作权归作者所有。请勿转载和采集!