該案例實現主要使用遞歸的思想,遞歸對新人來容易迷惑的是本身調用本身,直到知足條件爲止,接下來咱們就一步一步實現一個動態多級菜單vue組件css
搭建項目並安裝element-uihtml
npm i -g vue-cli vue init webpack myproject-name cd myproject-name/ npm install npm i element-ui -S
不是本文重點 自行查看element-ui官網vue
在main.js中引入element-uiwebpack
import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import App from './App.vue' Vue.use(ElementUI) new Vue({ el: '#app', render: h => h(App) })
編寫菜單樹組件 menutreeweb
<template> <div class="menutree"> <label v-for="menu in data" :key="menu.index"> <el-submenu :index="menu.index" v-if="menu.children"> <template slot="title"> <span>{{menu.name}}</span> </template> <label> <menutree :data="menu.children"></menutree> </label> </el-submenu> <el-menu-item v-else :index="menu.index"> <span slot="title">{{menu.name}}</span> </el-menu-item> </label> </div> </template>
<script> import menutree from "@/views/home/menutree"; export default { name: "menutree", data() { return { menu_data: {} }; }, components: { menutree: menutree }, props: ["data"], }; </script>
代碼分析
for循環全部的菜單,若是沒有子菜單則建立menuitem,不然建立submenu,而且把該子菜單做爲數據從新for循環,直到沒有子菜單,循環結束vue-cli
設計菜單數據npm
"menu_data": [{ "index": "1", "name": "用戶管理", "children": [{ "index": "1-2", "name": "用戶列表", "children": [{ "index": "1-2-1", "name": "用戶列表查詢", "children": [{ "index": "1-2-1-1", "name": "用戶列表查詢", "children": [{ "index": "1-2-1-1-1", "name": "用戶列表查詢", "children": [{ "index": "1-2-1-1-1-1", "name": "用戶列表查詢" }] }] }] }] }] }, { "index": "2", "name": "角色管理" }, { "index": "3", "name": "用戶管理" }, { "index": "4", "name": "角色管理" }] }
僅爲測試數據element-ui
其餘組件調用
html <template> <div class="left"> <el-menu> <menutree :data="menu_data"></menutree> </el-menu> </div> </template>
json
import menutree from "@/views/home/menutree"; import { home } from "@/config/init.json"; export default { components: { menutree: menutree }, data() { return { menu_data: {} }; }, mounted() { this.menu_data = home.left.menu_data; } }; </script>
實現效果bash
有任何疑問或建議歡迎留言