0 day streak
javascript / expert
Snippet

VNode Augmentation via Render Functions

Manually manipulating VNodes allows for the creation of Higher-Order Components that inject behavior or styles into slot content without adding extra DOM wrapper elements. This technique uses cloneVNode to merge new properties into existing virtual nodes.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { h, cloneVNode, defineComponent } from 'vue';
export const AugmentedWrapper = defineComponent({
setup(_, { slots }) {
return () => {
const defaultSlot = slots.default?.() || [];
return defaultSlot.map(vnode =>
cloneVNode(vnode, {
onVnodeMounted: () => console.log('Node mounted'),
class: 'enhanced-vnode'
})
);
};
}
});
vue
Breakdown
1
slots.default?.()
Executes the default slot function to retrieve the array of child VNodes.
2
cloneVNode(vnode, { ... })
Creates a shallow copy of the VNode while merging in new lifecycle hooks or attributes.