Vue3 - AntDesignVue 实现 动态面包屑 带 icon 图标

276 阅读1分钟

设置路由中的 mete

  • 路由中的配置
  • 通过配置 meta 让我们拿到面包屑所需的名称 + icon 图标
// router/index.ts
import { HomeOutlined, GlobalOutlined } from '@ant-design/icons-vue';
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/site",
      name: "site",
      component: () => import("../views/SiteView.vue"),
      meta: {
        path: "site",
        breadcrumbName: "网站",
        icon: GlobalOutlined,
      },
      children: [
        {
          path: "site02",
          name: "site02",
          component: () => import("../views/SiteView02.vue"),
          meta: {
            path: "site02",
            breadcrumbName: "网站02",
          },
        },
      ],
    },
  ],
});

配置组件

  • 面包屑组件
  • 通过 Ant Design Vuebreadcrumb 定义面包屑
  • 通过 route.matched 拿到路由中的 meta
  • 利用动态组件 component 设置动态图标 icon
<template>
  <a-breadcrumb style="margin: 16px 0" :routes="breadcrumb">
    <template #itemRender="{ route, paths }">
      <span v-if="breadcrumb.indexOf(route) === breadcrumb.length - 1">
        <!-- 如果是当前位置,则不需要跳转 -->
        <component :is="route.icon"></component>
        {{ route.breadcrumbName }}
      </span>
      <router-link v-else :to="`/${paths.join('/')}`">
        <component :is="route.icon"></component>
        {{ route.breadcrumbName }}
      </router-link>
    </template>
  </a-breadcrumb>
</template>
<script lang="ts" setup>
import { HomeOutlined } from "@ant-design/icons-vue";
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();

// 面包屑参数
const breadcrumb = computed(() => {
  let matchedArr = route.matched.map((item) => item.meta);
  if (matchedArr[0].breadcrumbName !== "首页") {
    // 因为 router.matched 不会携带第一个,我们需要给组件添加一个默认首页; 
    const first = {
      path: "/",
      breadcrumbName: "首页",
      icon: HomeOutlined,
    };
    matchedArr.unshift(first);
  }
  return matchedArr;
});
</script>

展示效果

001.png