当前位置: 首页 > 工具软件 > Naive UI > 使用案例 >

Naive ui:菜单 Menu批量处理图标替换自定义图片

江仲渊
2023-12-01

n-menu自带的图标使用xicons图标库,使用方法参考官网和naive ui,项目中使用的是自定义的图标,把需要使用的图标保存到本地,使用 render-icon 批量处理菜单图标渲染

1、新建一个菜单组件

<n-menu
    :collapsed-width="64"
    :collapsed-icon-size="22"
    :options="menus"
    :default-value="activeValue"
    :render-icon="renderMenuIcon"
    @update:value="handleUpdateValue"
  />

2、新建一个js文件,把需要用到的图标引入到项目文件中


// 菜单图标
import homeIcon from "@/assets/images/menu/icon-home.svg";
import cxzxIcon from "@/assets/images/menu/icon-cxzx.svg";
import Icon from "@/assets/images/menu/icon-xxx.svg";
import Icon0 from "@/assets/images/menu/icon-xx9.svg";
import Icon9 from "@/assets/images/menu/icon-xx8.svg";
import Icon8 from "@/assets/images/menu/icon-x8.svg";
import Icon7 from "@/assets/images/menu/icon-x7.svg";
import Icon6 from "@/assets/images/menu/icon-x6.svg";
import Icon5 from "@/assets/images/menu/icon-x5.svg";
import Icon4 from "@/assets/images/menu/icon-x4.svg";
import Icon3 from "@/assets/images/menu/icon-x3.svg";
import Icon2 from "@/assets/images/menu/icon-x2.svg";
import Icon1 from "@/assets/images/menu/icon-x1.svg";

const menuMap = {
  // ...
  menuIcons: [
    {
      icon: homeIcon,
      name: "首页",
    },
    {
      icon: Icon,
      name: "菜单名称",
    },
    {
      icon: Icon0,
      name: "菜单名称",
    },
    {
      icon: Icon9,
      name: "菜单名称",
    },
    {
      icon: Icon8,
      name: "菜单名称",
    },
    {
      icon: Icon7,
      name: "菜单名称",
    },
    {
      icon: Icon6,
      name: "菜单名称",
    },
    {
      icon: Icon5,
      name: "菜单名称",
    },
    {
      icon: Icon4,
      name: "菜单名称",
    },
    {
      icon: Icon3,
      name: "菜单名称",
    },
    {
      icon: Icon2,
      name: "菜单名称",
    },
    {
      icon: Icon1,
      name: "菜单名称",
    },
    {
      icon: cxzxIcon,
      name: "菜单名称",
    },
  ],
};

export default menuMap;

2、菜单组件中引入js文件,渲染图标

// 全局挂载
import useCurrentInstance from "@/hooks/useCuInstance.js"
const { $router, $utils, $dicts } = useCurrentInstance()

// 菜单图标库
const menuIconArr = $dicts.menuIcons
menus.value = menus.value.reduce((tmp, item) => {
  const obj = menuIconArr.find(icon => icon.name === item.label)
  return tmp.concat(Object.assign({}, item, { icon: obj.icon }))
}, [])

// 批量渲染菜单svg图标
function renderMenuIcon(option) {
  if (option.icon) {
    return h(
      "img",
      { src: option.icon, width: 24, height: 24 },
      { default: () => null }
    )
  } else {
    return null
  }
}

大功告成!

 类似资料: