javascript / expert
Snippet
Dynamic VNode Array Transformation using Functional Render Functions
This snippet demonstrates programmatic virtual DOM manipulation in Vue 3 by returning a render function from setup(). Using native JavaScript array operations like filter() and map(), children VNodes passed via slots are filtered and wrapped into new VNode elements dynamically.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { defineComponent, h, VNode } from 'vue';export const DynamicGroup = defineComponent({name: 'DynamicGroup',setup(_, { slots }) {return () => {const defaultNodes: VNode[] = slots.default ? slots.default() : [];const wrappedChildren = defaultNodes.filter((vnode) => typeof vnode.type !== 'symbol').map((vnode, index) => {return h('div', { key: vnode.key ?? index, class: 'group-item' }, [vnode]);});return h('section', { class: 'dynamic-group' }, wrappedChildren);};}});
vue
Breakdown
1
setup(_, { slots }) {
Accesses component slots within Composition API setup without requiring template compiler options.
2
const defaultNodes: VNode[] = slots.default ? slots.default() : [];
Retrieves the array of raw Virtual DOM nodes passed into the default component slot.
3
.filter((vnode) => typeof vnode.type !== 'symbol')
Filters VNode array elements to remove Fragment or Comment nodes using node type checks.
4
.map((vnode, index) => {
Transforms each raw child VNode into a uniquely keyed wrapper DOM node via array mapping.
5
return h('div', { key: vnode.key ?? index, class: 'group-item' }, [vnode]);
Utilizes Vue's h() hyperscript function to construct wrapped structural element nodes dynamically.
6
return h('section', { class: 'dynamic-group' }, wrappedChildren);
Renders the parent container wrapping all array-transformed VNodes into a single DOM element tree.