函数式组件
函数式组件是没有实例和状态的纯函数。
Vue 2 写法
JavaScript
export default {
functional: true,
render(h, context) {
return h('div', context.props.content)
}
}
Vue 3 写法
JavaScript
const FunctionalComp = (props, context) => {
return h('div', props.content)
}
接收上下文
JavaScript
const FunctionalComp = (props, { attrs, slots, emit }) => {
return h('div', { ...attrs }, slots.default())
}
单文件组件
vue
<script setup>
const props = defineProps(['content'])
</script>
<template>
<div>{{ props.content }}</div>
</template>
Vue 3 的 <script setup> 默认接近函数式组件性能。
函数式组件不能拥有响应式状态(data)或生命周期。
性能对比
| 类型 | 实例化 | 状态 | 性能 |
|---|---|---|---|
| 普通组件 | 是 | 支持 | 标准 |
| 函数式组件 | 否 | 不支持 | 更快 |
要点总结
- 函数式组件无实例、无状态
- 适合纯展示组件
- Vue 3 使用普通函数或
<script setup> - 渲染开销比普通组件低
📝 发现内容有误?点击此处直接编辑