使用element的NavMenu组件+vue的组件递归实现动态生成菜单。

首先创建对象记录菜单的标题、链接、子集等信息。

menus: [
    {
      title: "首页",
      icon: "el-icon-menu",
      link: "/index",
      remarks: "",
      subMenu: [],
    },
    {
      title: "系统管理",
      icon: "el-icon-message",
      link: "2",
      remarks: "",
      subMenu: [
        {
          title: "平台资源",
          link: "/index/Platformresources",
          remarks: "",
          subMenu: [],
        },
        {
          title: "用户管理",
          link: "/index/usermanagement",
          remarks: "",
          subMenu: [],
        },
        {
          title: "辅助功能",
          link: "1-3",
          remarks: "",
          subMenu: [
            {
              title: "分类管理",
              link: "/index/monogram",
              remarks: "",
              subMenu: [],
            },
            {
              title: "接口管理",
              link: "/index/interfacemanagement",
              remarks: "",
              subMenu: [],
            },
          ],
        },
      ],
    },
    {
      title: "配置管理",
      icon: "el-icon-menu",
      link: "/index/configurationmanagement",
      remarks: "",
      subMenu: [],
    },
    {
      title: "安装部署",
      icon: "el-icon-menu",
      link: "/index/Installdeploy",
      remarks: "",
      subMenu: [],
    }
  ],

创建menuModule组件用于生成菜单组件,使用div包裹<el-submenu />组件进行循环渲染,如果包含子级菜单(也就是menus数组中的subMenu数组数量大于0)则渲染<el-submenu />,反之渲染<el-menu-item />。当渲染<el-submenu />的子级时直接调用menuModule组件进行递归渲染实现动态生成菜单。

<div>
    <div v-for="item in menus" :key="item.title">
      <el-submenu
        :index="item.link"
        v-if="item.subMenu && item.subMenu.length > 0"
      >
        <template slot="title"
          ><i :class="filterData(item.icon)"></i>{{ item.title }}</template
        >
        <el-menu-item-group>
          <menu-module :menus="item.subMenu" />
        </el-menu-item-group>
      </el-submenu>
      <el-menu-item v-else :index="item.link">
        <i v-if="filterData(item.icon)" :class="filterData(item.icon)"></i>
        <span slot="title">{{ item.title }}</span>
      </el-menu-item>
    </div>
  </div>
<script>
import menuModule from "./menuModule.vue";
export default {
  name: "menu-module",
  components: { menuModule },
  props: {
    menus: {
      type: Array,
      default: [],
    },
  },
  methods: {
    filterData(data) {
      console.log(data);
      return data ? data : "";
    },
  },
};
</script>

Logo

前往低代码交流专区

更多推荐