首页 > 其他分享 >vue动态菜单创建icon

vue动态菜单创建icon

时间:2022-12-28 17:01:08浏览次数:49  
标签:vue icons title 菜单 path icon

如图,左侧的菜单是动态生成的,前面的icon图标也要动态创建

 

实现方法: 使用vue的 createVNode

定义一个生成icon的文件:  createIcon.js

import * as icons from "@ant-design/icons-vue";
import {
  createVNode
} from "vue";


// console.log(icons);

export const CreateIcon = (props) => {
  const {
    icon
  } = props;
  return createVNode(icons[icon]);
};

引入全部的icons, 根据当前菜单传入的名称,返回createVNode( name )

动态生成菜单的文件

<template>
  <template v-for="item in menuData">
    <a-menu-item
      :key="item.path"
      v-if="!item.children"
      @click="clickMenu(item.path)"
    >
      <template #icon v-if="item.icon">
        <CreateIcon :icon="item.icon" />
      </template>
      <span>{{ item.title }}</span>
    </a-menu-item>

    <a-sub-menu :key="item.path" v-else>
      <template #icon v-if="item.icon">
        <CreateIcon :icon="item.icon" />
      </template>
      <template #title>{{ item.title }}</template>
      <MenuItem :menuData="item.children" />
    </a-sub-menu>
  </template>
</template>

<script>
import menuData from "@/router/menu.js";
import { CreateIcon } from "../createIcon";
import { useRouter } from "vue-router";
export default {
  components: {
    CreateIcon,
  },
  name: "MenuItem",
  props: {
    menuData: {
      type: Array,
      default: () => menuData,
    },
  },
  setup() {
    const router = useRouter();
    const clickMenu = (path) => {
      router.push(path);
    };

    return {
      clickMenu,
    };
  },
};
</script>

使用: 将创建的icon文件引入,在需要图标的地方使用,传入相应的图标名称

菜单数据示例:

export default [{
    path: "/home",
    title: "首页",
    icon: "HomeOutlined",
  },
  {
    path: "/chart",
    title: "图表",
    icon: "GatewayOutlined",
    children: [{
      path: "/chart/pie",
      title: "多重环形图",
    }, ],
  },
  {
    path: "/vueinfo",
    title: "vue知识",
    icon: "FileTextOutlined",
    children: [{
        path: "/vueinfo/transfer",
        title: "组件动画",
      },
      {
        path: "/vueinfo/v-model",
        title: "v-model",
      },
      {
        path: "/vueinfo/global",
        title: "缓存与全局组件",
        meta: {
          keepAlive: true,
        },
      },
    ],
  },
];

这样就实现了icon的动态创建了

标签:vue,icons,title,菜单,path,icon
From: https://www.cnblogs.com/steamed-twisted-roll/p/17010527.html

相关文章