vue3中的defineProps 和 defineEmits
在 <script setup> 中必须使用 defineProps 和 defineEmits API 来声明 props 和 emits
<script setup>
const props = defineProps({
foo: String
})
//使用的时候用props.foo
const emit = defineEmits(['change', 'delete'])
// setup code
</script>
在Typescript中的用法(泛型):
const props = defineProps<{
foo: string
bar?: number //非必传
}>()
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
设置默认值(withDefaults)
interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})