Bird
Raised Fist0
Vueframework~7 mins

Recursive components in Vue

Choose your learning style10 modes available
Introduction

Recursive components let a component call itself to show nested or repeating data. This helps display things like trees or menus easily.

Showing a folder structure where folders can have subfolders inside them.
Displaying a nested comment section where comments can have replies.
Building a menu with items that can have sub-items.
Rendering a family tree with parents and children.
Syntax
Vue
<script setup>
import { defineProps } from 'vue'

const props = defineProps({
  item: Object
})
</script>

<template>
  <div>
    <p>{{ item.name }}</p>
    <ul v-if="item.children">
      <li v-for="child in item.children" :key="child.id">
        <RecursiveComponent :item="child" />
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'RecursiveComponent'
}
</script>

The component must have a name option to refer to itself.

Use props to pass data down to each recursive call.

Examples
Basic recursive component showing nested items with children.
Vue
<template>
  <div>
    <p>{{ item.name }}</p>
    <ul v-if="item.children">
      <li v-for="child in item.children" :key="child.id">
        <RecursiveComponent :item="child" />
      </li>
    </ul>
  </div>
</template>
Checks if children exist and have length to avoid empty lists.
Vue
<template>
  <div>
    <p>{{ item.name }}</p>
    <ul v-if="item.children && item.children.length">
      <li v-for="child in item.children" :key="child.id">
        <RecursiveComponent :item="child" />
      </li>
    </ul>
  </div>
</template>
Recursive component template using self-reference by name (no explicit import needed).
Vue
<template>
  <div>
    <p>{{ item.name }}</p>
    <ul v-if="item.children">
      <li v-for="child in item.children" :key="child.id">
        <RecursiveComponent :item="child" />
      </li>
    </ul>
  </div>
</template>
Sample Program

This example shows a tree structure with nested children. The RecursiveComponent calls itself to render each child node. The indentation grows with each level.

Vue
<script setup>
const treeData = {
  id: 1,
  name: 'Root',
  children: [
    {
      id: 2,
      name: 'Child 1',
      children: [
        { id: 3, name: 'Grandchild 1' },
        { id: 4, name: 'Grandchild 2' }
      ]
    },
    { id: 5, name: 'Child 2' }
  ]
}
</script>

<template>
  <RecursiveComponent :item="treeData" />
</template>

<script>
export default {
  name: 'App',
  components: {
    RecursiveComponent: () => import('./RecursiveComponent.vue')
  }
}
</script>
OutputSuccess
Important Notes

Recursive components can cause infinite loops if data is circular. Always ensure data ends.

Time complexity depends on the number of nodes; each node is rendered once.

Use recursive components when data is naturally nested and unknown depth.

Summary

Recursive components let a component call itself to show nested data.

They are great for trees, menus, and nested comments.

Always pass data via props and name the component for self-reference.

Practice

(1/5)
1. What is the main purpose of a recursive component in Vue?
easy
A. To handle user input events more efficiently
B. To create multiple unrelated components in one file
C. To optimize component rendering speed by caching
D. To allow a component to call itself to render nested or hierarchical data

Solution

  1. Step 1: Understand recursive component concept

    A recursive component is designed to call itself to handle nested or hierarchical data structures like trees or nested menus.
  2. Step 2: Compare options with definition

    Only To allow a component to call itself to render nested or hierarchical data correctly describes this behavior. Other options describe unrelated concepts.
  3. Final Answer:

    To allow a component to call itself to render nested or hierarchical data -> Option D
  4. Quick Check:

    Recursive component = self-calling component [OK]
Hint: Recursive means component calls itself for nested data [OK]
Common Mistakes:
  • Confusing recursion with event handling
  • Thinking recursive means multiple components in one file
  • Assuming recursion is about performance optimization
2. Which of the following is the correct way to name a recursive component in Vue 3 so it can call itself?
easy
A. const TreeNode = defineComponent({ components: { TreeNode }, ... })
B. const TreeNode = defineComponent({ setup() { return {}; } })
C. const TreeNode = defineComponent({ name: 'TreeNode', ... })
D. const TreeNode = defineComponent({ recursive: true, ... })

Solution

  1. Step 1: Identify how to enable self-reference

    Vue requires a component to have a name property to call itself recursively by that name.
  2. Step 2: Check options for correct naming

    const TreeNode = defineComponent({ name: 'TreeNode', ... }) correctly sets the name property. const TreeNode = defineComponent({ setup() { return {}; } }) lacks a name, C incorrectly tries to register itself as a child, and D uses a non-existent property.
  3. Final Answer:

    const TreeNode = defineComponent({ name: 'TreeNode', ... }) -> Option C
  4. Quick Check:

    Set component name for recursion [OK]
Hint: Name the component to enable self-reference [OK]
Common Mistakes:
  • Omitting the name property
  • Trying to register the component inside itself
  • Using invalid properties like 'recursive'
3. Given this recursive component snippet, what will be rendered if node has two children?
<template>
  <div>{{ node.name }}
    <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
  </div>
</template>
medium
A. The component renders the node's name and recursively renders each child node inside nested divs
B. Only the root node's name is rendered, children are ignored
C. An infinite loop occurs causing a crash
D. The component renders the node's name but children are rendered as plain text

Solution

  1. Step 1: Understand recursive rendering logic

    The component renders the current node's name, then for each child, it calls itself recursively, rendering nested divs for children.
  2. Step 2: Analyze output for two children

    With two children, the component renders the root node's name, then two nested TreeNode components, each rendering their own names and children recursively.
  3. Final Answer:

    The component renders the node's name and recursively renders each child node inside nested divs -> Option A
  4. Quick Check:

    Recursive call renders nested children [OK]
Hint: Recursive components render nested children inside themselves [OK]
Common Mistakes:
  • Assuming children are ignored
  • Thinking recursion causes infinite loop here
  • Expecting children as plain text instead of components
4. What is the main issue with this recursive component code?
<template>
  <div>{{ node.name }}
    <TreeNode v-for="child in node.children" :node="child" />
  </div>
</template>

<script>
export default {
  name: 'TreeNode',
  props: ['node']
}
</script>
medium
A. Props are not declared correctly, should use props: { node: Object }
B. Missing :key on v-for causing rendering warnings
C. The component lacks a name property for recursion
D. Recursive call will cause infinite loop without a base case

Solution

  1. Step 1: Check for common recursive component issues

    The code correctly names the component and declares props. The recursive call is valid.
  2. Step 2: Identify missing key in v-for

    Vue requires a unique :key on elements inside v-for for efficient rendering. This is missing, causing warnings.
  3. Final Answer:

    Missing :key on v-for causing rendering warnings -> Option B
  4. Quick Check:

    Always add :key in v-for loops [OK]
Hint: Always add :key in v-for to avoid warnings [OK]
Common Mistakes:
  • Thinking name property is missing
  • Believing props declaration is invalid
  • Assuming infinite loop without base case
5. You want to display a nested comment thread using a recursive component. Each comment may have zero or more replies. Which approach correctly prevents infinite recursion and handles empty children arrays?
hard
A. In the template, use <Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply" /> and ensure comment.replies defaults to an empty array if no replies
B. Render all comments without checking children, assuming replies always exist
C. Use a v-if to stop recursion when comment.replies is undefined, but do not default to empty array
D. Avoid recursion and flatten the comment tree before rendering

Solution

  1. Step 1: Understand recursion base case

    To prevent infinite recursion, the component must handle cases where there are no children by using an empty array or conditional rendering.
  2. Step 2: Analyze options for best practice

    In the template, use <Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply" /> and ensure comment.replies defaults to an empty array if no replies uses v-for with a key and ensures replies default to an empty array, preventing errors and infinite loops. Render all comments without checking children, assuming replies always exist ignores empty children, C risks errors without default, and A avoids recursion but is not recursive component usage.
  3. Final Answer:

    Use v-for with key and default empty array for replies -> Option A
  4. Quick Check:

    Default empty array stops infinite recursion [OK]
Hint: Default children to empty array to stop recursion errors [OK]
Common Mistakes:
  • Not providing default empty array for children
  • Assuming children always exist
  • Avoiding recursion when it's the best fit
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard