函数式组件剩下的唯一应用场景就是简单组件,比如创建动态标题的组件。否则,建议你像平常一样使用有状态组件。
<!-- 函数式组件 -->
<Functional level="2">这是一个函数式组件</Functional>
Vue3.0写法
1、单文件组件
<template>
<component :is="`h${$props.level}`" v-bind="$attrs">
<slot></slot>
</component>
</template>
<script>
export default {
name: 'Heading',
props: ['level']
};
</script>
2、通过函数创建组件
它们将接收两个参数:props 和 context。context 参数是一个对象,包含组件的 attrs、slots 和 emit property。
<script>
import { h } from 'vue';
const Heading = function (props, context) {
const { attrs, emit, slots } = context;
return h(`h${props.level}`, attrs, slots);
};
Heading.props = ['level'];
export default Heading;
</script>
通过对比可以发现,通过函数创建组件,可读性更高。