Functional Components in Vue.js
oaltena
Posted on November 12, 2018
Although Vue.js is basically very performant, each additional component uses memory resources. Not every component needs its own Vue instance and change detection. The use of functional components can save resources.
Functional components do not receive a Vue instance at runtime. Rather, such components behave as if they were part of the higher-level component. Functional components are therefore particularly suitable for simple and generic UI components such as buttons, list elements or dropdown controls. A practical example of a functional component is the placeholder for routing views .
You can create functional components by adding the attribute functional in the template tag with a template. However, developers often implement functional components with their own render functions.
A functional component does not have its own instance and therefore no this context. To access properties, event handlers, and other definitions, a functional component is given an object context.
An exemplary render function is structured as a functional component as follows:
export default {
name: 'SimpleList',
functional: true,
props: {
items: Array
},
render(h, context) {
return h("ul", context.props.items.map(item => h("li", item)))
}
}
The render function gets the object context as second attribute and the access to the array is now not done with this.items, but with context.props.items.
After importing the component, you can use it as follows:
<template>
<div>
<SimpleList :items="languages"/>
</div>
</template>
<script>
import SimpleList from './SimpleList'
export default {
data() {
return {
languages: ['German', 'French', 'Italian']
}
},
components: {
SimpleList
}
}
</script>
Output:
- German
- French
- Italian
Posted on November 12, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.