search
HomeWeb Front-endJS TutorialHow to build a recursive component into a tree menu in Vue.js

This time I will show you how Vue.js builds recursive components into tree menus. What are the precautions for Vue.js to build recursive components into tree menus? The following are Let’s take a look at practical cases.

In Vue.js, a recursive component calls itself, such as:

Vue.component('recursive-component', {
 template: `<!--Invoking myself!-->
    <recursive-component></recursive-component>
 });

Recursive components are often used to display comments on blogs, nested menus, or basically the same type as parent and child, although the specific content is different.

Now to show you how to use recursive components effectively, I will proceed step by step by building an expandable/collapse tree menu.

data structure

A recursive component of a tree UI would be a visual representation of some recursive data structure. In this tutorial we will use a tree structure where each node is an object:

A label attribute.

If it has child nodes, a nodes property is an array property of one or more nodes.

Like all tree structures, it must have a root node, but can be infinitely deep.

let tree = {
 label: 'root',
 nodes: [
  {
  label: 'item1',
  nodes: [
   {
   label: 'item1.1'
   },
   {
   label: 'item1.2',
   nodes: [
    {
    label: 'item1.2.1'
    }
   ]
   }
  ]
  }, 
  {
  label: 'item2' 
  }
 ]
 }

Recursive components

Let's make a recursive component to display our data structure called TreeMenu. It only displays the current node's label, and calls itself to display any child nodes. File name: TreeMenu.vue, content is as follows:

<template>
 <p>
  </p>
<p>{{ label }}</p>
  <tree-menu>
  </tree-menu>
 
 </template>
 <script>
 export default { 
  props: [ &#39;label&#39;, &#39;nodes&#39; ],
  name: &#39;tree-menu&#39;
 }
 </script>

If you use a component recursively, you must first give Vue.component a global definition, or give it a name attribute. Otherwise, any child component will not be able to call it further and you will get an undefined "undefined component error" error message.

Basic events

As with any recursive function, you need a base event to end the recursion, otherwise rendering will continue indefinitely, eventually causing a stack overflow.

In the tree menu, we want to stop the recursion when we reach a node that has no children. You can do this with v-if, but we choose to use v-for This will be implemented for us implicitly; if the nodes array doesn't have any further definition the tree-menu component will be called. The template.vue file is as follows:

<template>
 <p>
  ...
  <!--If `nodes` is undefined this will not render-->
  <tree-menu></tree-menu>
 </p></template>

Usage

How do we use this component now? First, we declare a Vue instance with a data structure including the data attribute and the defined treemenu component. The app.js file is as follows:

 import TreeMenu from './TreeMenu.vue'
 let tree = {
 ...
 }
 new Vue({
 el: '#app',
 data: {
  tree
 },
 components: {
  TreeMenu
 }
 })

Remember, our data structure has a root node. We start calling the TreeMenu component recursively from the main template, using the root nodes attribute to props:

<p>
 <tree-menu></tree-menu>
 </p>

It's good to visually identify the "depth" of subcomponents so users can get a feel for the data structure from the UI. Let's achieve this by indenting the child nodes at each level.

This is achieved by adding a depth prop definition through TreeMenu. We will use this value to dynamically bind inline styles with transforms: we will use the transform: translate CSS rule for each node's label, thus creating an indent. template.vue is modified as follows**:**

<template>
 <p>
  </p>
<p>{{ label }}</p>
  <tree-menu>
  </tree-menu>
 
 </template>
 <script>
 export default { 
  props: [ &#39;label&#39;, &#39;nodes&#39;, &#39;depth&#39; ],
  name: &#39;tree-menu&#39;,
  computed: {
  indent() {
   return { transform: `translate(${this.depth * 50}px)` }
  }
  }
 }
 </script>

The depth attribute starts from zero in the main template. In the component template above, you can see that this value is incremented every time it is passed to any child node.

<p>
 <tree-menu></tree-menu>
 </p>

Note: Remember to v-bind the depth value to ensure it is a JavaScript number type and not a string.

Expand/Collapse

Because recursive data structures can be large, a good UI trick for displaying them is to hide all nodes except the root node so that the user can expand or collapse the nodes as needed.

To do this, we will add a local property showChildren. If its value is False, the child node will not be rendered. This value should be toggled by clicking on the node, so we need to use a click event listener method toggleChildren to manage it. The template.vue file is modified as follows**:**

<template>
 <p>
  </p>
<p>{{ label }}</p>
  <tree-menu>
  </tree-menu>
 
 </template>
 <script>
 export default { 
  props: [ &#39;label&#39;, &#39;nodes&#39;, &#39;depth&#39; ],
  data() {
  return { showChildren: false }
  },
  name: &#39;tree-menu&#39;,
  computed: {
  indent() {
   return { transform: `translate(${this.depth * 50}px)` }
  }
  },
  methods: {
  toggleChildren() {
   this.showChildren = !this.showChildren;
  }
  }
 }
 </script>

Summarize

This way, we have a working tree menu. As a finishing touch, you can add a plus/minus icon to make the UI more visible. I also added very good fonts and computing performance based on the original showChildren

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

How to use JSONAPI in PHP

How to use VueRouter’s navigation guard

The above is the detailed content of How to build a recursive component into a tree menu in Vue.js. 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft