uni-app+vue3+uVIew-plus封装动态权限TabBar

1,527 阅读1分钟

首先,pages.json中需要根据你的页面配置tabBar

    {
        "pages": [...],
        "tabBar": { // 设置底部 tab 的表现
                "color": "#333333",
                "borderStyle": "black",
                "backgroundColor": "#fff",
                "list": [{
                        "text": "首页",
                        "pagePath": "pages/index/index"
                    }, {
                        "text": "管理",
                        "pagePath": "pages/manage/manage"
                 }]
          }
    }
    

其次,是我们的基于uView-plus自定义的tabBar组件, 存放在@/components/TabBar/TabBar.vue。

<template>
	<u-tabbar 
        :value="selected" 
        @change="name => selected = name" 
        fixed  
        safeAreaInsetBottom>
		<u-tabbar-item 
                    v-for="item in getTabBarList" 
                    :key="item.pagePath" 
                    :text="item.text" 
                    :icon="item.iconPath"
                    @click="click(item)"
           ></u-tabbar-item>
	</u-tabbar>
</template>

<script setup lang="ts">
	import { useUserStore } from "@/store/plugins";
	import { storeToRefs } from 'pinia';
	import {
		defineProps,
		withDefaults,
		toRefs
	} from 'vue';

	const userStore = useUserStore();
	const { getTabBarList } = storeToRefs(userStore);

	type Prop = {
		selected : number
	};
	const props = withDefaults(defineProps<Prop>(), {
		selected: 0
	});
	let { selected } = toRefs(props);

	const click = (item) => {
		uni.switchTab({
			url: item.pagePath
		})
	}
</script>

接着,是getTabBarList,这个我是通过pinia,getter属性获取。vuex,同理。

import { defineStore } from "pinia"
import { UserState } from "./types";
import tabBar from '@/utils/tabBarList';
const userStore = defineStore('user', {
	state: () : UserState => ({
		role: 'admin',
	}),
	getters: {
		getTabBarList() {
			return tabBar[this.role];
		}
	},
	actions: {
	}
})

export default userStore;

最后,是配置权限表,放在*@/utils/tabBarList**。*

const ROLES = {
	ADMIN: 'admin',
	USER: 'user',
	TEACHER: 'teacher'
};
//需要注意的是pagePath是绝对路径,前面需要加/,与pages.json中不同。
export default {
	[ROLES.USER]: [{
		iconPath: "home",
		text: '首页',
		pagePath: '/pages/index/index',
	}],
	[ROLES.ADMIN]: [{
		iconPath: "home",
		text: '首页',
		pagePath: '/pages/index/index',
	}, {
		iconPath: "home",
		text: '管理',
		pagePath: '/pages/manage/manage',
	},]
};

在需要TabBar的页面中直接引入就好。

<template>
	<view>
		<TabBar :selected="selected"></TabBar>
	</view>
</template>

<script setup>
	import TabBar from "@/components/TabBar/TabBar";
	
	let selected = 1;
</script>

<style lang="scss">

</style>

*在App.vue中,记得使用uni.hideTabBar()将原生的tabBar隐藏掉。 *

<script>
	export default {
		onLaunch: function() {
			console.warn('当前组件仅支持 uni_modules 目录结构 ,请升级 HBuilderX 到 3.1.0 版本以上!')
			console.log('App Launch')
			uni.hideTabBar()
		},
		onShow: function() {
			console.log('App Show')
			uni.hideTabBar()
		},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>