vue3.2/Vite/Ts26: 处理左侧导航菜单图标
·
Yin灏
将所有的 Icon 图标变为全局注册
- src / components / index.ts
//...
// 引入全局的 element plus 的图标
// M
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
//...
export default {
install(app: any) {
//...
// M
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
},
};
//...
给每一个路由对象再添加一个 icon 字段
- src / router / routes.ts
export const contantRoute = [
{
path: "/login",
component: () => import("@/views/login/index.vue"),
name: "login",
meta: {
title: "登录",
hidden: true,
// M
icon: "xxx", // 菜单左侧图标
},
},
{
path: "/",
component: () => import("@/layout/index.vue"),
name: "layout",
meta: {
title: "layout",
hidden: false,
// M
icon: "xxx",
},
children: [
{
path: "/home",
component: () => import("@/views/home/index.vue"),
meta: {
title: "首页",
hidden: false,
// M
icon: "xxx",
},
},
],
},
{
path: "/404",
component: () => import("@/views/404/index.vue"),
name: "404",
meta: {
title: "404",
hidden: true,
// M
icon: "xxx",
},
},
{
path: "/:pathMatch(.*)*",
redirect: "/404",
name: "Any",
meta: {
title: "任意路由",
hidden: true,
// M
icon: "xxx",
},
},
];
添加图标
- src / layout / menu / index.vue
<template>
<template v-for="(item, index) in menuList" :key="item.path">
<template v-if="!item.children">
<el-menu-item
v-if="!item.meta.hidden"
:index="item.path"
@click="goRoute"
>
<!-- M -->
<!-- el-icon 放在 template #title 外面 -->
<el-icon>
<component :is="item.meta.icon"></component>
</el-icon>
<template #title>
<!-- M -->
<span>{{ item.meta.title }}</span>
</template>
</el-menu-item>
</template>
<template v-if="item?.children?.length === 1">
<el-menu-item
v-if="!item.children[0].meta.hidden"
:index="item.children[0].path"
@click="goRoute"
>
<!-- M -->
<!-- el-icon 放在 template #title 外面 -->
<el-icon>
<component :is="iitem.children[0].meta.icon"></component>
</el-icon>
<template #title>
<span>{{ item.children[0].meta.title }}</span>
</template>
</el-menu-item>
</template>
<el-sub-menu v-if="item?.children?.length > 1" :index="item.path">
<template #title>
<!-- M -->
<el-icon>
<component :is="item.meta.icon"></component>
</el-icon>
<span>{{ item.meta.title }}</span>
</template>
<menu :menuList="item.children"></menu>
</el-sub-menu>
</template>
</template>
<script setup lang="ts">
defineProps(["menuList"]);
//引入路由器
import { useRouter } from "vue-router";
let $router = useRouter();
// 点击菜单跳转
const goRoute = (vc: any) => {
// 二级路由跳转
// consoel.log(vc)
$router.push(vc.index);
};
</script>
<script lang="ts">
export default {
name: "Menu",
};
</script>