Introduction to Render Functions
# What is a Vue render function?
You're probably used to write Vue components in Single File Components (SFC) format:
<template>
<div>Hello world</div>
</template>
…where you put all your HTML inside the template
block.
Vue has an HTML-based template engine, and what it does is transform these templates into “render functions”.
Render functions are the JavaScript representation of a Vue template.
Just so you know, Vue compiles the previous example into something like:
function render( ) {
with(this){
return _c('div',[_v("Hello World")])
}
}
But more generally, when we talk about render functions, we talk about the way of authoring templates with the following syntax:
<script>
// Vue 2 syntax
export default {
render(h) { // <- Render Function
return h('div', ['hello world']) // <- This is our template
}
}
</script>
So, for components defined with render functions, there's no need to have a template
block at all, because the template is defined in the render
function.
To get to know this syntax better, please refer to the official docs: https://vuejs.org/v2/guide/render-function.html
# Vue 3 syntax
Now let's write the previous example with Vue 3 syntax:
<script>
// Vue 3 syntax
import { h } from 'vue'
export default {
render() {
return h('div', ['hello world'])
}
}
</script>
What changed is that now we need to import the h
function from Vue
manually. It's no longer passed as a parameter to the render
function by default.
Here's a link to the Vue (3) SFC Playground to see this in action:
# Differences with regular templates
- With render functions, performance is not increased or even degraded.
- File size differences are marginal.
- Readability is worse in render function components.
- Therefore, maintainability is harder.
- And it makes it more difficult for folks not used to JavaScript (or Vue render functions) to contribute.
So, if it makes them harder to maintain and the performance is not significantly improved, why do we want them, why do we need them? In the next article, we're going to see a few cases where render functions are actually needed and recommended. Stay tuned!
Related Articles
When to use a Vue Render Function
When should I use a render function in Vue.js? We’re going to cover some advanced Vue.js patterns when you need to use render functions.
Jan 27, 2022
When to use a Vue Render Function
When should I use a render function in Vue.js? We’re going to cover some advanced Vue.js patterns when you need to use render functions.
Jan 27, 2022
Run watchers when a Vue.js component is created
Tutorial on how to make a watcher run instantly when a Vue.js component is created
Mar 31, 2019
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.