Skip to content

Commit dbc89dd

Browse files
authored
Add example for typing functional components (#2352)
1 parent 35bffdc commit dbc89dd

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

src/guide/extras/render-function.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,3 +739,78 @@ MyComponent.inheritAttrs = false
739739
```
740740

741741
Functional components can be registered and consumed just like normal components. If you pass a function as the first argument to `h()`, it will be treated as a functional component.
742+
743+
### Typing Functional Components<sup class="vt-badge ts" /> {#typing-functional-components}
744+
745+
Functional Components can be typed based on whether they are named or anonymous. Volar also supports type checking properly typed functional components when consuming them in SFC templates.
746+
747+
**Named Functional Component**
748+
749+
```tsx
750+
import type { SetupContext } from 'vue'
751+
type FComponentProps = {
752+
message: string
753+
}
754+
755+
type Events = {
756+
sendMessage(message: string): void
757+
}
758+
759+
function FComponent(
760+
props: FComponentProps,
761+
context: SetupContext<Events>
762+
) {
763+
return (
764+
<button onClick={() => context.emit('sendMessage', props.message)}>
765+
{props.message} {' '}
766+
</button>
767+
)
768+
}
769+
770+
FComponent.props = {
771+
message: {
772+
type: String,
773+
required: true
774+
}
775+
}
776+
777+
FComponent.emits = {
778+
sendMessage: (value: unknown) => typeof value === 'string'
779+
}
780+
```
781+
782+
**Anonymous Functional Component**
783+
784+
```tsx
785+
import type { FunctionalComponent } from 'vue'
786+
787+
type FComponentProps = {
788+
message: string
789+
}
790+
791+
type Events = {
792+
sendMessage(message: string): void
793+
}
794+
795+
const FComponent: FunctionalComponent<FComponentProps, Events> = (
796+
props,
797+
context
798+
) => {
799+
return (
800+
<button onClick={() => context.emit('sendMessage', props.message)}>
801+
  {props.message} {' '}
802+
</button>
803+
)
804+
}
805+
806+
FComponent.props = {
807+
message: {
808+
type: String,
809+
required: true
810+
}
811+
}
812+
813+
FComponent.emits = {
814+
sendMessage: (value) => typeof value === 'string'
815+
}
816+
```

0 commit comments

Comments
 (0)