Bootstrap

vue3+Element Plus功能组件封装——顶部导航(动态渲染+样式调整)

网页顶部的导航栏,一般由代码动态生成

菜单数据在文件内统一配置,方便增删改查,导入后可自动生成导航菜单

代码如下

1.dom部分(简单示例)

<el-menu mode="horizontal" :default-active="currentPath" router
				@select="selectedMenu"
				style="border-bottom: none;width: 1250px;background-color: #073371;height: 80px;">
				<div v-for="(navMenu,index) in menuList" :key="index">
					<el-menu-item v-if="!navMenu.children" :index="navMenu.key">
						{{ navMenu.title }}
					</el-menu-item>
				<el-sub-menu v-if="navMenu.children" :index="index.toString()" class="mu_submenu">
						<template #title>{{navMenu.title}}</template>
					<el-menu-item v-for="subMenu in navMenu.children"                     :index="subMenu.key">
							{{ subMenu.title }}
				</el-menu-item>
		</el-sub-menu>
	</div>
</el-menu>

<script setup>
import {
		ref,
		onMounted,
		computed,
		reactive,
		watch
	} from 'vue'
import {
		useRouter,
		useRoute
	} from 'vue-router'
    let currentPath = ref('')
	onMounted(() => {
		let route = useRoute()
		currentPath.value = route.path
	})

const menuList = ref([
    {
	id: 1,
	title: "page1",
	key: '/path1',
}, {
	id: 2,
	title: "page2",
	children: [{
		id: 3,
		title: "page2-1",
		key: '/path21'
	}, {
		id: 4,
		title: "page2-2",
		key: '/path22'
	}]
}
])

</script>

2.css部分

以下样式分为两个style,没有scope限制的样式用于控制二级菜单弹出层的宽度,因为需要脱离scope限制,如果有多个页面用到可放在父级页面样式中,如App.vue

<style scoped>
	:deep(.el-menu-item),
	:deep(.el-sub-menu__title) {
		background: #073371 !important;
		color: #7EA4DD;
		font-size: 18px;
		font-weight: bold;
		height: 80px;
	}
</style>
<style>
	/* 导航菜单设置样式*/
	.el-menu--collapse .el-menu .el-submenu,
	.el-menu--popup {
		min-width: 100px !important;
		padding: 0 15px !important;
		border: none !important;
		text-align: center !important;
	}
</style>

修改前————>>>修改后

3.菜单高亮(重点选中二级菜单时高亮)

一级菜单实现,可按需求添加背景图

.el-menu .el-menu-item.is-active {
		/* background: url('../assets/other/activemenu.png') 0px 57px !important; */
		/* background-repeat: no-repeat !important; */
		/* background-position: 0 0; */
		background-color: #08336F !important;
		color: aliceblue !important;
	}

 二级菜单实现,通过计算当前导航索引动态添加类

:class="currentActiveIndex==index? 'activeSubmenu':'defaultSubmenu'"

分别为激活和未激活设置不同的样式,提升用户体验

:deep(.el-menu .activeSubmenu .el-sub-menu__title){
	color: aliceblue !important;
	/*background: url('../assets/other/activemenu.png') 0px 57px !important;
	background-repeat: no-repeat !important;
	background-position: 0 0;*/
	}
:deep(.el-menu .defaultSubmenu .el-sub-menu__title) {
	color: #7EA4DD !important;
}

以上即可动态渲染导航菜单,如果为垂直,修改mode模式即可。

;