Simple and performant functional Vue.js components

#Vue

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!

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.

Alex

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