Function defineProps() & defineEmits()
To declare options like props
and emits
with full
type inference support, we can use the defineProps
and defineEmits
APIs, which are automatically
available inside <script setup>
:
<script setup>
const props = defineProps({
foo: String
})
const emit = defineEmits(['change', 'delete'])
// setup code
</script>
defineProps
and defineEmits
are compiler
macros only usable inside <script setup>
. They do
not need to be imported, and are compiled away
when <script setup>
is processed.
Type-only props/emit declarations Typescript
const props = defineProps<{
foo: string
bar?: number
}>()
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
// 3.3+: alternative, more succinct syntax
const emit = defineEmits<{
change: [id: number] // named tuple syntax
update: [value: string]
}>()