Simple and performant functional Vue.js components
Sometimes we don't need complex components, and in some cases we don't even need them to have a state on its own. That can be the case when building UI components that don't have much logic in it.
For cases like that, functional components can be very appropriated. They're stateless and instanceless, which means that it doesn't even have an instance on its own (so no way to call this.$emit and such).
That makes them simple to reason about, faster and more lightweight.
The question is, when can I use a functional component? Easy: when they depend only on props.
As an example, the following component:
<template>
<div>
<p v-for="item in items" @click="$emit('item-clicked', item)">
{{ item }}
</p>
</div>
</template>
<script>
export default {
props: ["items"]
};
</script>
Could be written in a functional way as follows:
<template functional>
<div>
<p v-for="item in props.items" @click="props.itemClick(item);">
{{ item }}
</p>
</div>
</template>
Pay attention to the things that changed:
- Write
functionalin thetemplatetag - Props are accessible via
props - Since we don't have access to
$emit, we can use a function as a prop. That's how the React community has done it the whole time and it worked pretty well. - No need for the
scriptpart
Do you want to see it in action? Check it out yourself in this CodeSandbox!
Related Articles
Auto Load Vuejs Components in Nuxt
Tired of writing imports all over your code? Read this tutorial to learn how to use Nuxt components module to automatically import your components
Jun 17, 2020
How to structure a Vue.js app using Atomic Design and TailwindCSS
Unsure about how to organize your Vue.js components? Learn in this tutorial how to do it using Atomic Design methodology. Examples and demos included!
Jun 16, 2020
The most modern Pie Chart component using CSS Conic Gradient and Vue.js
Build a Pie Chart component using one of the modern CSS features Conic Gradient
Oct 21, 2019
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

