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 functional in the template tag
  • 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 script part

Do you want to see it in action? Check it out yourself in this CodeSandbox!

Don't miss out anything about Vue, your favourite framework.

Subscribe to receive all the articles we publish in a concise format, perfect for busy devs.

Related Articles

Achieve Max Performance loading your images with v-lazy-image

Don't you know what to do to improve your web performance? Learn Progressive Image Loading, a technique used by Spotify, Medium and Netflix.

Alex Jover Morales

Alex Jover Morales

Aug 30, 2021

Use Responsive Images with v-lazy-image

Is Web Performance a priority for you? Then read this article! You'll learn how to lazy load images with srcset and picture tag using v-lazy-image.

Alex Jover Morales

Alex Jover Morales

Aug 23, 2021

Use Web Workers in your Vue.js Components for Max Performance

Learn how to get up to 20x performance improvement of Vue.js components that rely on heavy tasks so they render and load faster

Alex Jover Morales

Alex Jover Morales

Mar 31, 2020

Sponsors

VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.

Silver
Learning Partner