Home  >  Article  >  Web Front-end  >  How to use Vue to implement a multi-level navigation menu?

How to use Vue to implement a multi-level navigation menu?

WBOY
WBOYOriginal
2023-06-25 09:13:303270browse

With the development of the Internet, more and more websites need to implement multi-level navigation menus to display various categories and sub-categories to facilitate users' browsing and use. In the front-end framework, Vue also provides good support to help us implement multi-level navigation menus. This article will introduce how to use Vue to implement a multi-level navigation menu.

1. Basic concepts

Before using Vue to implement multi-level navigation menus, we need to understand some basic concepts:

  1. Node (node): tree structure Each element in is called a node.
  2. Root node (root node): The top-most node in the tree structure is called the root node.
  3. Leaf node: A node that has no child nodes in the tree structure is called a leaf node.
  4. Parent node: A node with child nodes is called a parent node.
  5. Child node: A node that is contained by a parent node and appears as its direct descendant is called a child node.

2. Data structure design

To implement a multi-level navigation menu in Vue, we need to define a data structure to store the menu data. We can use JSON format to store menu data. We need to define the following properties for each menu item:

  1. id: Each menu item needs to have a unique id.
  2. title: The title of the menu.
  3. icon: The icon of the menu.
  4. path: Menu link.
  5. children: data of the next-level menu. If the current menu is a leaf node, children is an empty array.

The following is a simple multi-level menu data example:

[
  {
    "id": 1,
    "title": "菜单 1",
    "icon": "fa fa-home",
    "path": "/menu1",
    "children": [
      {
        "id": 11,
        "title": "菜单 1-1",
        "icon": "fa fa-book",
        "path": "/menu1-1",
        "children": [
          {
            "id": 111,
            "title": "菜单 1-1-1",
            "icon": "fa fa-link",
            "path": "/menu1-1-1",
            "children": []
          },
          {
            "id": 112,
            "title": "菜单 1-1-2",
            "icon": "fa fa-link",
            "path": "/menu1-1-2",
            "children": []
          }
        ]
      },
      {
        "id": 12,
        "title": "菜单 1-2",
        "icon": "fa fa-book",
        "path": "/menu1-2",
        "children": []
      }
    ]
  },
  {
    "id": 2,
    "title": "菜单 2",
    "icon": "fa fa-home",
    "path": "/menu2",
    "children": [
      {
        "id": 21,
        "title": "菜单 2-1",
        "icon": "fa fa-book",
        "path": "/menu2-1",
        "children": []
      },
      {
        "id": 22,
        "title": "菜单 2-2",
        "icon": "fa fa-book",
        "path": "/menu2-2",
        "children": []
      }
    ]
  }
]

3. Component design

To implement multi-level navigation menus in Vue, we can use components to build. Since the multi-level navigation menu is a tree structure, we can use recursive components to create a tree-structured menu. A recursive component is when a component calls itself within its template.

  1. Menu component

The Menu component is our root component, which calls the MenuItem component to create menu items and set styles according to different levels.

<template>
  <ul class="menu">
    <menu-item
      v-for="(item, index) in list"
      :key="item.id"
      :item="item"
      :level="1"
      :last="index === list.length - 1"
    ></menu-item>
  </ul>
</template>

<script>
import MenuItem from './MenuItem.vue';

export default {
  name: 'Menu',
  components: {
    MenuItem,
  },
  props: {
    list: {
      type: Array,
      required: true,
    },
  },
};
</script>

<style scoped>
.menu {
  padding: 0;
  margin: 0;
}
</style>
  1. MenuItem component

The MenuItem component creates menu items based on the incoming menu data and determines whether the current menu item has a next-level menu item. If so, Then the next-level menu is created recursively, otherwise the link address of the current menu item is displayed.

<template>
  <li :class="{'has-children': hasChildren}">
    <router-link :to="item.path"><i :class="item.icon"></i>{{ item.title }}</router-link>
    <ul v-if="hasChildren">
      <menu-item
        v-for="(child, index) in item.children"
        :key="child.id"
        :item="child"
        :level="level + 1"
        :last="index === item.children.length - 1"
      ></menu-item>
    </ul>
  </li>
</template>

<script>
import MenuItem from './MenuItem.vue';

export default {
  name: 'MenuItem',
  components: {
    MenuItem,
  },
  props: {
    item: {
      type: Object,
      required: true,
    },
    level: {
      type: Number,
      required: true,
    },
    last: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    hasChildren() {
      return this.item.children && this.item.children.length > 0;
    },
    indent() {
      return {
        paddingLeft: `${this.level * 20}px`,
        borderBottom: this.last ? 'none' : '',
      };
    },
  },
};
</script>

<style scoped>
.has-children {
  position: relative;
}

li i {
  margin-right: 5px;
}

ul {
  margin: 0;
  padding: 0;
}

li {
  list-style: none;
}

li:last-child {
  border-bottom: none;
}
</style>

4. Use cases

Next we will use the multi-level navigation menu component we created in a Vue project.

  1. Create Vue project

We can use Vue CLI to create a Vue project:

npm install -g @vue/cli
vue create my-project
  1. Install Vue routing

We need to use Vue routing to manage page jumps:

npm install vue-router --save
  1. Configuring Vue routing

We need to configure routing in the Vue project to separate different Routing jumps to different pages. Set the path of the route to the path defined in the menu data. When the user clicks on the menu item, they will jump from / to the corresponding page.

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    component: About,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;
  1. Rendering multi-level navigation menu

We can use the Menu component in the page to render the multi-level navigation menu.

<template>
  <div id="app">
    <menu :list="menu"></menu>
    <router-view></router-view>
  </div>
</template>

<script>
import Menu from './components/Menu.vue';

export default {
  name: 'App',
  components: {
    Menu,
  },
  data() {
    return {
      menu: [
        {
          id: 1,
          title: '首页',
          icon: 'fa fa-home',
          path: '/home',
          children: [],
        },
        {
          id: 2,
          title: '关于我们',
          icon: 'fa fa-info',
          path: '/about',
          children: [],
        },
        {
          id: 3,
          title: '产品分类',
          icon: 'fa fa-product-hunt',
          path: '',
          children: [
            {
              id: 31,
              title: '手机',
              icon: 'fa fa-mobile',
              path: '/products/mobile',
              children: [
                {
                  id: 311,
                  title: '苹果',
                  icon: 'fa fa-apple',
                  path: '/products/mobile/apple',
                  children: [
                    {
                      id: 3111,
                      title: 'iPhone 12',
                      icon: 'fa fa-gift',
                      path: '/products/mobile/apple/iphone-12',
                      children: [],
                    },
                    {
                      id: 3112,
                      title: 'iPhone 11',
                      icon: 'fa fa-gift',
                      path: '/products/mobile/apple/iphone-11',
                      children: [],
                    },
                  ],
                },
                {
                  id: 312,
                  title: '华为',
                  icon: 'fa fa-huawei',
                  path: '/products/mobile/huawei',
                  children: [
                    {
                      id: 3121,
                      title: 'Mate 40 Pro',
                      icon: 'fa fa-gift',
                      path: '/products/mobile/huawei/mate-40-pro',
                      children: [],
                    },
                    {
                      id: 3122,
                      title: 'P40',
                      icon: 'fa fa-gift',
                      path: '/products/mobile/huawei/p40',
                      children: [],
                    },
                  ],
                },
              ],
            },
            {
              id: 32,
              title: '电脑',
              icon: 'fa fa-desktop',
              path: '/products/computer',
              children: [
                {
                  id: 321,
                  title: '联想',
                  icon: 'fa fa-link',
                  path: '/products/computer/lenovo',
                  children: [
                    {
                      id: 3211,
                      title: 'ThinkPad X1',
                      icon: 'fa fa-gift',
                      path: '/products/computer/lenovo/thinkpad-x1',
                      children: [],
                    },
                    {
                      id: 3212,
                      title: 'IdeaPad 5',
                      icon: 'fa fa-gift',
                      path: '/products/computer/lenovo/ideapad-5',
                      children: [],
                    },
                  ],
                },
                {
                  id: 322,
                  title: '戴尔',
                  icon: 'fa fa-dell',
                  path: '/products/computer/dell',
                  children: [
                    {
                      id: 3221,
                      title: 'XPS 13',
                      icon: 'fa fa-gift',
                      path: '/products/computer/dell/xps-13',
                      children: [],
                    },
                    {
                      id: 3222,
                      title: 'Inspiron 14 7000',
                      icon: 'fa fa-gift',
                      path: '/products/computer/dell/inspiron-14-7000',
                      children: [],
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    };
  },
};
</script>

5. Summary

Vue provides good support to help us implement multi-level navigation menus. Using recursive components to create tree-structured menus can make the code simpler and easier to understand. When designing menu data, you need to pay attention to the naming of attributes and the hierarchical relationship of the menu, which helps us better implement multi-level navigation menus in recursive components.

The above is the detailed content of How to use Vue to implement a multi-level navigation menu?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn