0
0
Vueframework~30 mins

Recursive components in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Building a Recursive Tree Component in Vue
📖 Scenario: You are creating a simple file explorer tree. Each folder can contain files or other folders. You want to display this structure using a recursive Vue component.
🎯 Goal: Build a recursive Vue component called TreeNode that displays a nested folder and file structure. Each folder can expand to show its children.
📋 What You'll Learn
Create a data structure representing folders and files with nested children
Add a boolean isOpen property to control folder expansion
Use a recursive TreeNode component to render folders and files
Add a toggle button to open and close folders
💡 Why This Matters
🌍 Real World
File explorers, menus, organizational charts, and any nested hierarchical data display use recursive components.
💼 Career
Understanding recursive components is key for frontend developers building complex UI trees and navigation structures.
Progress0 / 4 steps
1
Create the initial nested data structure
Create a constant called fileTree with this exact nested structure: a folder named root containing two children: a folder named src with children main.js and App.vue, and a file named README.md. Use objects with name, type ('folder' or 'file'), and children (array) properties.
Vue
Hint

Think of folders as objects with a children array, and files as objects without children.

2
Add an isOpen property to folders
Add an isOpen property set to false to each folder object in fileTree and its nested folders. Do not add isOpen to files.
Vue
Hint

Only folders have isOpen. Files do not.

3
Create the recursive TreeNode component
Create a Vue component named TreeNode using <script setup>. It accepts a prop called node. If node.type is 'folder', render the folder name with a button to toggle node.isOpen. If node.isOpen is true, recursively render TreeNode for each child in node.children. If node.type is 'file', just render the file name.
Vue
Hint

Use defineProps to accept node. Use a button to toggle node.isOpen. Use recursion by including <TreeNode> inside itself.

4
Use TreeNode in the main app
In the main Vue app component, import TreeNode and render it once with the fileTree object as the node prop.
Vue
Hint

Import the recursive component and pass the root data as a prop.