javascript / expert
Snippet
Recursive Functional Components for High-Performance Trees
Functional components in Vue 3 (simple functions returning VNodes) are stateless and highly efficient for rendering deep, recursive structures like file trees or nested menus. Using the 'h' function directly avoids template compilation overhead for every recursive step.
snippet.js
javascript
1
2
3
4
5
6
const Tree = (props, { slots }) => {return h('div', props.data.map(item => [h('span', item.label),item.children && h(Tree, { data: item.children })]));};
vue
Breakdown
1
const Tree = (props, { slots }) => {
Defines a functional component that accepts props and context.
2
return h('div', props.data.map(item => [
Creates a root VNode and iterates over the data array.
3
item.children && h(Tree, { data: item.children })
Recursively invokes the component itself if nested children exist.