在vue3.0+router4.0+ant 3.00-aipha.11里,将路由里面的Icon图标引入到导航菜单里面

657 阅读2分钟

    最近在试着开发一个vue3.0的平台,平常上会遇到一些个乱七八糟的没见过或者一些其他问题,刚好记录一下自己的问题解决日常。学艺不精,多多指教。

    如题,这次遇到的问题是在匹配动态路由到菜单栏的时候考虑到Icon组件的引入。 在以往的vue2.x里面,常见的路由引入是这种情况:

router.js

 {
     path: "/form",
     name: "form",
     component: { render: h => h("router-view") },
     meta: { icon: "form", title: "表单", authority: ["admin"] },
 }

    meta放入对应的 icon ,菜单名和权限

在侧边栏siderMenu里面的使用

<template v-for="item in menuData">
        <a-menu-item
          v-if="!item.children"
          :key="item.path"
          @click="() => $router.push({ path: item.path, query: $route.query })"
        >
          <a-icon v-if="item.meta.icon" :type="item.meta.icon" /> // 这里引用
          <span>{{ item.meta.title }}</span>
        </a-menu-item>
        <sub-menu v-else :menu-info="item" :key="item.path" />
      </template>

这时候的icon是通过ant自身携带api来引入,可以看一下ant1.x关于ant的api.

企业微信截图_16367665295501.png

    但是ant这种用法明显是不适用于现在的vue3.0的版本。我们此时对比一下ant 3.00-aipha.11里面的Icon的api和他的用法。

此时的Icon是以组件的形式引入的,官方留下的基本用法是:

//通过 @ant-design/icons-vue 引用 Icon 组件,不同主题的 Icon 组件名为图标名加主题做为后缀,也可以通过设置 spin 属性来实现动画旋转效果。
<template>
  <div class="icons-list">
    <HomeOutlined />
  </div>
</template>
<script>
import { defineComponent } from 'vue';
import { HomeOutlined} from '@ant-design/icons-vue';
export default defineComponent({
  components: {
    HomeOutlined,
  },
});
</script>

    此时的icon就是作为一个组件来引入的,这时候明显就不能按照vue2.x的这种方法来引入了。我们可以想一下,现在的icon已经是一个组件了,那作为上面这种正常式的传入组件,还有一种传入组件的方法:动态组件。

    找下文档,实现的方法很简单:可以通过 Vue 的 <component> 元素加一个特殊的 is attribute 来实现。留下文档地址

[cn.vuejs.org/v2/guide/co…]   

尝试在我们现在的项目里面使用

router.js

import { MenuFoldOutlined} from "@ant-design/icons-vue";
​
{
    name: "welcome",
    path: "/welcome",
    meta: {
        title: "欢迎页",
        icon: MenuFoldOutlined,
    },
    component: () => import("../views/welcome.vue"),
}

在侧边栏里:

<a-menu-item v-if="!menu.children" :key="menu.path" @click="menuClick(menu.path)" >
    <template #icon>
         <component :is="menu.meta.icon"></component>
    </template>
    <span>{{ menu.meta.title }}</span>
</a-menu-item>

Icon出现,解决。这边暂时是使用这个方法,有其他大佬有其他方法欢迎评论区讨论。