Performance: Recursive components
Recursive components impact rendering performance by increasing DOM depth and triggering multiple layout calculations during recursive rendering.
<template> <TreeNode :node="rootNode" /> </template> <script setup> import { reactive } from 'vue' import TreeNode from './TreeNode.vue' const rootNode = reactive({ id: 1, children: [/* large nested data */] }) </script> <!-- TreeNode.vue --> <script setup> defineOptions({ name: 'TreeNode' }) const props = defineProps({ node: Object }) </script> <template> <div> <span>{{ node.id }}</span> <template v-if="node.children && node.children.length"> <TreeNode v-for="child in node.children" :key="child.id" :node="child" /> </template> </div> </template>
<template> <TreeNode :node="rootNode" /> </template> <script setup> import { reactive } from 'vue' import TreeNode from './TreeNode.vue' const rootNode = reactive({ id: 1, children: [/* large nested data */] }) </script> <!-- TreeNode.vue --> <script setup> defineOptions({ name: 'TreeNode' }) const props = defineProps({ node: Object }) </script> <template> <div> <span>{{ node.id }}</span> <TreeNode v-for="child in node.children" :key="child.id" :node="child" /> </div> </template>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Deep recursive rendering without conditions | High (many nested nodes) | High (one per node) | High (complex paint) | [X] Bad |
| Recursive rendering with conditional checks | Medium (skips empty nodes) | Medium (fewer reflows) | Medium (simpler paint) | [!] OK |
recursive component in Vue?name property to call itself recursively by that name.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.node has two children?<template>
<div>{{ node.name }}
<TreeNode v-for="child in node.children" :key="child.id" :node="child" />
</div>
</template>TreeNode components, each rendering their own names and children recursively.<template>
<div>{{ node.name }}
<TreeNode v-for="child in node.children" :node="child" />
</div>
</template>
<script>
export default {
name: 'TreeNode',
props: ['node']
}
</script>:key on elements inside v-for for efficient rendering. This is missing, causing warnings.<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.Pass the test and this pattern moves unknown