Performance: Functional components
Functional components affect rendering speed and memory usage by reducing component overhead in Vue apps.
<script setup> export default (props) => { return h('div', props.text) } </script>
<script> export default { name: 'BadComponent', data() { return { count: 0 } }, template: `<div>{{ count }}</div>` } </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full component with state | More nodes due to reactive wrappers | Multiple reflows if state changes | Higher paint cost due to updates | [X] Bad |
| Functional component (stateless) | Minimal nodes, no reactive wrappers | Single reflow per render | Lower paint cost | [OK] Good |
functional component in Vue?<script setup> syntax in Vue 3?<script setup>, functional components can be defined as functions returning VNodes using the h helper.<script setup>\nimport { h } from 'vue'\nconst MyFuncComp = (props) => h('div', props.text)\n</script> correctly defines a functional component returning a div with text using h. <script setup>\nconst MyFuncComp = (props) => <div>{props.text}</div>\n</script> uses JSX-like syntax which is not default in Vue. Options B and C use options API syntax incorrectly inside <script setup>.<script setup>
import { h } from 'vue'
const Greeting = (props) => h('p', `Hello, ${props.name}!`)
</script>
<template>
<Greeting name="Alice" />
</template>name.name="Alice", it renders <p>Hello, Alice!</p> as a normal HTML element.<script setup>
const Button = (props) => {
return <button>{props.label}</button>
}
</script><button>{props.label}</button>) inside a function without JSX support configured.h() helper or templates unless JSX is set up. Without JSX setup, this causes a syntax error.<script setup> and the h function?h function, you can create an unordered list with list items by mapping over the items array and creating li elements.<script setup>
import { h } from 'vue'
const ItemList = (props) => h('ul', props.items.map(item => h('li', item)))
</script> correctly maps each item to an li element inside a ul. <script setup>
const ItemList = { functional: true, props: ['items'], template: '<ul><li v-for="item in items">{{ item }}</li></ul>' }
</script> uses options API incorrectly inside <script setup>. <script setup>
const ItemList = (props) => {
return <ul>{props.items.map(item => <li>{item}</li>)} uses JSX without setup. <script setup>
import { h } from 'vue'
const ItemList = (props) => h('ul', [h('li', props.items)])
</script> incorrectly passes the whole array as a single li.Pass the test and this pattern moves unknown