Performance: h function for creating vnodes
This affects how Vue creates virtual DOM nodes, impacting rendering speed and memory usage during component updates.
import { h } from 'vue'; const items = ['Item 1', 'Item 2', 'Item 3']; export default { render() { return h('div', {}, items.map(item => h('p', {}, item))); } };
import { h } from 'vue'; export default { render() { return h('div', {}, [ h('p', {}, 'Item 1'), h('p', {}, 'Item 2'), h('p', {}, 'Item 3') ]); } };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual multiple h calls without abstraction | Many vnode creations | Multiple reflows on updates | Higher paint cost due to frequent DOM changes | [X] Bad |
| Using array map to batch vnode creation | Fewer vnode creations, batched | Single reflow per update batch | Lower paint cost with minimal DOM changes | [OK] Good |
h function in Vue?h in Vueh function is used to create virtual nodes (vnodes) which represent elements or components in Vue's virtual DOM.div element with the h function and a class of "container"?h function signatureh function takes the tag name as the first argument and an object of props as the second argument.class (not className) as the key for CSS classes in the props object.return h('ul', null, [
h('li', null, 'Apple'),
h('li', null, 'Banana'),
h('li', null, 'Cherry')
])hh creates a ul element with an array of li children nodes.li vnode contains a string child representing the fruit name, so the final HTML is a list with three li items.h function:
return h('button', { onclick: () => alert('Clicked!') }, 'Click me')hh function to create a ul list from this array of fruits, but only include fruits with names longer than 5 characters?
const fruits = ['Apple', 'Banana', 'Fig', 'Cherry']
filter to keep only fruits with names longer than 5 characters.li vnodesmap to convert each filtered fruit into an li vnode with the fruit name as child.li vnodes as children to ulul with only the desired fruits as list items.Pass the test and this pattern moves unknown