search
HomeWeb Front-endVue.jsHow to use Vue to implement a multi-level navigation menu?

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
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version