javascript / expert
Snippet
Functional Tree Components with h()
For highly dynamic or recursive structures, templates can be restrictive. Functional components using the 'h' (hyperscript) function offer better control over render logic and slightly better performance for pure-presentational nodes without instance overhead.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { h, resolveComponent } from 'vue';const RecursiveTree = (props) => {const children = props.items.map(item => {return h('div', { class: 'node' }, [h('span', item.label),item.children ? h(resolveComponent('RecursiveTree'), { items: item.children }) : null]);});return h('div', { class: 'tree-root' }, children);};RecursiveTree.props = ['items'];export default RecursiveTree;
vue
Breakdown
1
h(resolveComponent('RecursiveTree'), ...)
Recursively renders the same component by resolving its name.
2
RecursiveTree.props = ['items']
Explicitly defines props for a functional component.