>  기사  >  웹 프론트엔드  >  Vue를 사용하여 다단계 탐색 메뉴를 구현하는 방법은 무엇입니까?

Vue를 사용하여 다단계 탐색 메뉴를 구현하는 방법은 무엇입니까?

WBOY
WBOY원래의
2023-06-25 09:13:303228검색

인터넷이 발전함에 따라 점점 더 많은 웹사이트에서 사용자의 탐색과 사용을 용이하게 하기 위해 다양한 카테고리와 하위 카테고리를 표시하는 다단계 탐색 메뉴를 구현해야 합니다. 프런트엔드 프레임워크에서 Vue는 다단계 탐색 메뉴를 구현하는 데 도움이 되는 훌륭한 지원도 제공합니다. 이 기사에서는 Vue를 사용하여 다단계 탐색 메뉴를 구현하는 방법을 소개합니다.

1. 기본 개념

Vue를 사용하여 다단계 탐색 메뉴를 구현하기 전에 몇 가지 기본 개념을 이해해야 합니다.

  1. 노드(노드): 트리 구조의 각 요소를 노드라고 합니다.
  2. 루트 노드: 트리 구조의 최상위 노드를 루트 노드라고 합니다.
  3. 리프 노드: 트리 구조에서 하위 노드가 없는 노드를 리프 노드라고 합니다.
  4. 부모 노드: 자식 노드가 있는 노드를 부모 노드라고 합니다.
  5. 자식 노드: 상위 노드에 포함되고 직계 자손으로 나타나는 노드를 하위 노드라고 합니다.

2. 데이터 구조 설계

Vue에서 다단계 탐색 메뉴를 구현하려면 메뉴 데이터를 저장할 데이터 구조를 정의해야 합니다. JSON 형식을 사용하여 메뉴 데이터를 저장할 수 있습니다. 각 메뉴 항목에 대해 다음 속성을 정의해야 합니다.

  1. id: 각 메뉴 항목에는 고유한 ID가 있어야 합니다.
  2. title: 메뉴의 제목입니다.
  3. icon: 메뉴의 아이콘입니다.
  4. 경로: 메뉴 링크.
  5. children: 다음 레벨 메뉴의 데이터입니다. 현재 메뉴가 리프 노드인 경우 children은 빈 배열입니다.

다음은 간단한 다단계 메뉴 데이터 예입니다.

[
  {
    "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. 구성 요소 디자인

Vue에서 다단계 탐색 메뉴를 구현하려면 구성 요소를 사용하여 빌드할 수 있습니다. 다단계 탐색 메뉴는 트리 구조이므로 재귀 구성 요소를 사용하여 트리 구조 메뉴를 만들 수 있습니다. 재귀 구성 요소는 구성 요소가 템플릿 내에서 자신을 호출하는 경우입니다.

  1. Menu 구성 요소

Menu 구성 요소는 MenuItem 구성 요소를 호출하여 메뉴 항목을 만들고 다양한 수준에 따라 스타일을 설정하는 루트 구성 요소입니다.

<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 구성 요소

MenuItem 구성 요소는 수신된 메뉴 데이터를 기반으로 메뉴 항목을 생성하고 현재 메뉴 항목에 다음 수준 메뉴 항목이 있는지 여부를 결정합니다. 그렇다면 다음 수준 메뉴가 재귀적으로 생성됩니다. 현재 메뉴의 항목 링크 주소가 표시됩니다.

<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. 사용 사례

다음으로 Vue 프로젝트에서 만든 다중 레벨 탐색 메뉴 구성 요소를 사용하겠습니다.

  1. Vue 프로젝트 만들기

Vue CLI를 사용하여 Vue 프로젝트를 만들 수 있습니다.

npm install -g @vue/cli
vue create my-project
  1. Vue 라우팅 설치

페이지 점프를 관리하려면 Vue 라우팅을 사용해야 합니다.

npm install vue-router --save
  1. Vue 라우팅 구성

다른 경로를 다른 페이지로 이동하려면 Vue 프로젝트에서 라우팅을 구성해야 합니다. 메뉴 데이터에 정의된 경로로 경로를 설정합니다. 사용자가 메뉴 항목을 클릭하면 해당 페이지에서/으로 이동합니다.

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. 다단계 탐색 메뉴 렌더링

페이지의 메뉴 구성요소를 사용하여 다단계 탐색 메뉴를 렌더링할 수 있습니다.

<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. 요약

Vue는 다단계 탐색 메뉴를 구현하는 데 도움이 되는 훌륭한 지원을 제공합니다. 재귀 구성 요소를 사용하여 트리 구조의 메뉴를 만들면 코드를 더 간단하고 이해하기 쉽게 만들 수 있습니다. 메뉴 데이터를 디자인할 때 속성 이름 지정과 메뉴의 계층적 관계에 주의를 기울여야 합니다. 이는 재귀 구성 요소에서 다단계 탐색 메뉴를 더 잘 구현하는 데 도움이 됩니다.

위 내용은 Vue를 사용하여 다단계 탐색 메뉴를 구현하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.