Vue3 render() Function
render() The function is a very important function in Vue 3; its role is to generate the component's virtual DOM, which is a lightweight JavaScript object Vue uses to describe the real DOM.
Pass render() function, Vue can efficiently update and render the page.
Relationship with Templates
In Vue, we usually usethe templateto define the component's structure. The template is eventually compiled into the render() function. Therefore,render() function is the underlying implementation of the template.
Use Cases
render() The function is typically used in the following scenarios:
- When you need to dynamically generate the component structure.
- When you need to directly manipulate the DOM.
- In high-performance scenarios, to manually optimize rendering logic.
Basic Syntax of the render() Function
render() The function receives one parameter: Vue's h function (also called the createElement function), used to create virtual DOM nodes.
Example
export
default
{
render
(
h
)
{
return
h
(
'div'
,
{
class
:
'container'
}
,
'Hello, Vue3!'
)
;
}
}
Parameter Description
- The first parameter: Tag name or component name (string or component object).
- The second parameter: Attribute object (optional), used to define DOM attributes, events, etc.
- The third parameter: Child nodes (optional), which can be a string, array, or other virtual DOM nodes.
Advanced Usage of the render() Function
Dynamically Generate Child Nodes
render() The function can dynamically generate child nodes based on data.
Example
export
default
{
data
(
)
{
return
{
items
:
[
'Apple'
,
'Banana'
,
'Orange'
]
}
}
,
render
(
h
)
{
return
h
(
'ul'
,
this
.
items
.
map
(
item
=>
h
(
'li'
,
item
)
)
)
;
}
}
Using Slots
render() The function can access slot content via this.$slots .
Example
export
default
{
render
(
h
)
{
return
h
(
'div'
,
[
h
(
'header'
,
this
.$slots.
header
)
,
h
(
'main'
,
this
.$slots.
default
)
,
h
(
'footer'
,
this
.$slots.
footer
)
]
)
;
}
}
Rendering Components
render() The function can directly render other components.
Example
import
MyComponent from
'./MyComponent.vue'
;
export
default
{
render
(
h
)
{
return
h
(
MyComponent
,
{
props
:
{
message
:
'Hello from parent!'
}
}
)
;
}
}
Optimizing the render() Function
Reduce Unnecessary Rendering
Pass render() function, you can manually control the component's rendering logic and avoid unnecessary DOM updates.
Example
export
default
{
data
(
)
{
return
{
showMessage
:
true
}
}
,
render
(
h
)
{
return
this
.
showMessage
?
h
(
'p'
,
'Hello!'
)
:
null
;
}
}
Using Fragment
Vue 3 supports Fragment, allowing the render() function to return multiple root nodes.
Example
export
default
{
render
(
h
)
{
return
[
h
(
'div'
,
'Left'
)
,
h
(
'div'
,
'Right'
)
]
;
}
}
Vue3 Options API