一文读懂uniapp中的tabBar底部导航

发布于:2024-04-18 ⋅ 阅读:(24) ⋅ 点赞:(0)

1. 基本知识

UniApp 中的 tabBar 是用来在应用程序底部显示可切换的选项卡的组件,通常用于实现底部导航栏

允许用户通过点击不同的选项卡来切换应用程序的不同页面或功能模块

在这里插入图片描述
其代码如下:

"tabBar":{
	"color":"#FFFFFF",
	"selectedColor":"#007AFF",
	"borderStyle":"black",
	"backgroundColor":"#20222a",
	"position":"bottom",
	"list":[{
			"pagePath": "pages/index/index",
			"iconPath":"static/index.png",
			"selectedIconPath":"static/index-selected.png",
			"text": "首页"
		}, {
			"pagePath": "pages/index/reportPage",
			"iconPath":"static/statistics.png",
			"selectedIconPath":"static/statistics-selected.png",
			"text": "统计"
		},{
			"pagePath": "pages/index/morePage",
			"iconPath":"static/more.png",
			"selectedIconPath":"static/more-selected.png",
			"text": "更多"
		}
	]
},

对应的组件属性如下:

  • list: tabBar 的列表,每个选项卡都包含了图标、文字和对应的页面路径
  • color:选项卡未被选中时的颜色
  • selectedColor:选项卡被选中时的颜色
  • backgroundColor: tabBar 的背景颜色
  • borderStyle: tabBar 的边框样式
  • position: tabBar 的位置,可选值包括 top(顶部)和 bottom(底部)

2. Demo

设计的整体逻辑如下:

一、在 app.json 文件中配置 tabBar 字段
定义了 tabBar 的整体样式和行为,包括了颜色、选中颜色、边框样式、背景颜色和位置等属性
配置列表中的各个 tabBarItem,指定每个选项卡的页面路径、图标路径、选中图标路径和文字, 能够正确显示并响应用户的点击行为

二、在各个页面的 JSON 配置文件中设置 navigationBarTitleText 字段
确保每个页面能够在顶部显示正确的标题,当用户访问不同的页面时,顶部标题栏将显示相应的标题,提供了良好的用户体验

三、创建对应的页面文件,并编写逻辑和界面
创建了三个页面文件:index.vue、reportPage.vue 和 morePage.vue,并在其中编写了相应的逻辑和界面,文件包含页面的布局、样式和与用户交互的逻辑

四、将 tabBar 的图标和文字资源放置到对应的路径下
为了让 tabBar 能够正确显示图标和文字,将资源放置到项目的指定路径下,例如 static 文件夹,并在 tabBar 的配置中引用这些资源路径,确保 tabBar 能够正确显示各个选项卡的图标和文字

其pages.json如下:

{
	"easycom": {
			"^u-(.*)": "uview-ui/components/u-$1/u-$1.vue"
	},
	"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
		
		{
		    "path" : "pages/login/login",
		    "style" :                                                                                    
		    {
				"transparentTitle":"always"
		    }
		}
    ],
	"tabBar":{
		"color":"#FFFFFF",
		"selectedColor":"#007AFF",
		"borderStyle":"black",
		"backgroundColor":"#20222a",
		"position":"bottom",
		"list":[{
				"pagePath": "pages/index/index",
				"iconPath":"static/index.png",
				"selectedIconPath":"static/index-selected.png",
				"text": "首页"
			}, {
				"pagePath": "pages/index/reportPage",
				"iconPath":"static/statistics.png",
				"selectedIconPath":"static/statistics-selected.png",
				"text": "统计"
			},{
				"pagePath": "pages/index/morePage",
				"iconPath":"static/more.png",
				"selectedIconPath":"static/more-selected.png",
				"text": "更多"
			}
		]
	},
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "equipment-app",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8"
	}
}