Vue3 render() function
render()The function is a very important function in Vue3; its purpose is to generate the virtual DOM of components. The virtual DOM is a lightweight JavaScript object that Vue uses to describe the real DOM.
Throughrender()function, Vue can efficiently update and render pages.
Relationship with templates
In Vue, we usually usetemplateto define the structure of a component. The template is ultimately compiled intorender()function. Therefore,render()function is the underlying implementation of the template.
Use cases
render()The function is usually used in the following scenarios:
- When component structure needs to be dynamically generated.
- When DOM needs to be manipulated directly.
- In scenarios with high performance requirements, manually optimize rendering logic.
Basic syntax of render() function
render()The function receives one parameter, Vue'shfunction (also calledcreateElementfunction), used to create virtual DOM nodes.
Example
render(h) {
return h('div', { class: 'container' }, 'Hello, Vue3!');
}
}
Parameter description
- First parameter: tag name or component name (string or component object).
- Second parameter: attributes object (optional), used to define DOM attributes, events, etc.
- Third parameter: child nodes (optional), can be a string, array, or other virtual DOM nodes.
Advanced usage of render() function
Dynamically generating child nodes
render()The function can dynamically generate child nodes based on data.
Example
data() {
return {
items: ['Apple', 'Banana', 'Orange']
}
},
render(h) {
return h('ul', this.items.map(item => h('li', item)));
}
}
Using slots
render()The function can, viathis.$slotsaccess slot content.
Example
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
export default {
render(h) {
return h(MyComponent, { props: { message: 'Hello from parent!' } });
}
}
Optimization of render() function
Reducing unnecessary renders
Throughrender()function, you can manually control the component's rendering logic to avoid unnecessary DOM updates.
Example
data() {
return {
showMessage: true
}
},
render(h) {
return this.showMessage ? h('p', 'Hello!') : null;
}
}
Using Fragment
Vue3 supportsFragment, and you canrender()return multiple root nodes in the function.
Example
render(h) {
return [h('div', 'Left'), h('div', 'Right')];
}
}
Other extensions
Vue3 Options API