5 min read
•Question 28 of 37hardWhat are Render Functions in Vue?
Programmatic component rendering.
What You'll Learn
- h() function
- When to use render functions
- JSX alternative
Basic Render Function
code.jsJavaScript
import { h } from 'vue'
export default {
setup() {
return () => h('div', { class: 'container' }, [
h('h1', 'Hello'),
h('p', 'World')
])
}
}h() Signature
code.jsJavaScript
h(
'div', // tag
{ class: 'foo' }, // props
[ // children
'text',
h('span', 'child')
]
)Dynamic Components
code.jsJavaScript
export default {
props: ['level'],
setup(props, { slots }) {
return () => h(
'h' + props.level, // h1, h2, h3...
{},
slots.default()
)
}
}JSX Alternative
code.txtJSX
// With @vitejs/plugin-vue-jsx
export default {
setup() {
const count = ref(0)
return () => (
<div>
<h1>Count: {count.value}</h1>
<button onClick={() => count.value++}>+</button>
</div>
)
}
}When to Use
- Highly dynamic components
- Component libraries
- When templates are limiting