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:

    <p v-for="item in items" @click="$emit('item-clicked', item)">
      {{ item }}

  export default {
    props: ["items"]

Could be written in a functional way as follows:

<template functional>
    <p v-for="item in props.items" @click="props.itemClick(item);">
      {{ item }}

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!

Remember you can read this tip online (with copy/pasteable code), and don’t forget to share VueDose with your colleagues, so they also know about these tips as well!

See you next week.


Start saving time and get a tip about the Vue ecosystem every week, right in your inbox.

Latest Vue Jobs