DEV Community

oaltena
oaltena

Posted on • Edited on

1

Functional Components in Vue.js

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More