首先把tabbar中的元素写在一个list中用v-for进行渲染
用一个interface进行定义接口,这样别人在review你的代码就可以清晰知道你的tabbar包含什么元素。
利用typescript特性进行类型定义,可以省去很多麻烦
import { reactive } from "vue"
import { Images } from "src/static/images"
export interface Tabbar {iconPath: string,selectedIconPath: string,text: string,url: string
}export const tabBarList = reactive<Tabbar[]>([{iconPath: Images.Home,selectedIconPath: Images.HomeActive,text: '首页',url: '/pages/home/home',},{iconPath: Images.Personal,selectedIconPath: Images.PersonalActive,text: '我的',url: '/pages/personal/personal',}
])
<template><view class="tabbar-container"><view v-for="(item, index) in tabBarList" :key="index" :url="item.url" :class="{ 'active': activeIndex === index }"><view class="icon-container" @click="switchTab(index)"><view class="icon"><image class="icon-image" :src="activeIndex === index ? item.selectedIconPath : item.iconPath" /></view><view class="text">{{ item.text }}</view></view></view></view>
</template>
渲染好之后,tabbar有个点击跳转页面,以及点亮图标
点亮图标,这边的currentPath一定注意格式,打印出getCurrentPages()[0].route就会发现它是pages/personal/personal,而不是/pages/personal/personal
//vue
<view class="icon"><image class="icon-image" :src="activeIndex === index ? item.selectedIconPath : item.iconPath" /></view>//jsconst currentPath = "/" + getCurrentPages()[0].route;
tabBarList.forEach((item, index) => {if (item.url === currentPath) {store.activeIndex = index;uni.switchTab({url: item.url,})}
})
跳转:由于是page页面,因此必须用switchtab方法而不能用nacigatorTo;这边的index及页面序号必须存储在pinia库中,否则界面一刷新它就不变了。
function switchTab(index) {if (index === store.activeIndex) {return}store.setActiveIndex(index)uni.switchTab({url: tabBarList[index].url})
}
import { defineStore } from 'pinia'interface State {activeIndex: number;sceneId: number;isLogin: boolean;nickname: string;avatar: string
}export const useTabbarStore = defineStore('store', {state: (): State => {return { activeIndex: 0,isLogin: false,sceneId: 1,nickname: '立即登录',avatar: 'https://bestwellai-aigo.oss-cn-shanghai.aliyuncs.com/icon/personal/personal_avatar.svg' }},actions: {setActiveIndex(index) {this.activeIndex = index;},setUsername(nickname,avatar){this.nickname = nickname;this.avatar = avatar;},setSceneId(sceneId) {this.sceneId = sceneId;}},
})
完成效果:自定义的效果就是样式可以自己写,非常方便;以及一个小程序需要三四种形式的tabbar时可以这样操作。