Scenario: Since the project needs a dynamic sidebar, you can’t write the navigation menu in the Element-UI

Combine the recursive component implementation in VUE, directly on the code

Sidebar of the parent component

<el-menu router class="el-menu-vertical-demo" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" >  <Menu v-for="(item, Index) in routerList" :key="index" :item="item" :path="item.path" ></Menu> </el-menu> // Menu is the introduced component routerList: [{name: "navigation", path: "1", the children: [{name: "1-1", path: "1-1", the children: [{name: "1-1-1", the path: "1-1-1", children: [ { name: "1-1-1-1", path: "1-1-1-1", children: [] } ] } ] }, { name: "1-2", path: "1-2", children: []}}, {name: "two" navigation, path: "2", the children: [{name: "2-1", path: "2-1", the children: [{name: "2-1-1", the path: "2-1-1", children: [] } ] } ] } ],Copy the code

Recursive subcomponent

// Menu component <el-menu-item :index="item.path" V-if ="item.children. Length <= 0"> < I class="el-icon-setting"></ I >< span slot="title">{{ item.name }}</span> </el-menu-item> <el-submenu :index="item.path" v-else> <template slot="title"> <i class="el-icon-location"></i> <span>{{ item.name }}</span> </template> <Menu v-for="child in item.children" :key="child.path" :item="child" :path="child.path" ></Menu> </el-submenu> <script> export default { name: "Menu", props: { item: { type: Object, required: true }, path: { type: String, default: "" } } }; </script>Copy the code

Because it is a dynamically set sidebar, all routerList formats must be an array. The parent component passes in a list and a fixed path, while the child component needs to determine whether there are children based on the length of the children for each item in the currently accepted list. When the length of children is 0, it means that the current item is el-menu-item (need to click display content); when the length of children is not 0, it means el-Submenu (click to expand the sub-item). Then in el-Submenu you can continue passing in the current component (Menu component) and each corresponding child for traversal. This creates a recursive component.

Note: there are two pits: 1. There must be a name attribute in the child component because recursion is required, because vUE states that to implement a recursive component, the recursive component needs to be identified by name. 2. As a recursive component, there must be an ‘exit’ based on the length of children