<script setup lang="ts">
.未指出的地方和使用原生ts一致
1、props
(1)运行时声明
.其他格式和选项式中props格式一致
const props = defineProps({
foo: { type: String, required: true },
bar: Number
})
(2)通过泛型
const props = defineProps<{
foo: string
bar?: number
}>()
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()
2、emit
(1)运行时声明
.其他格式和选项式中emits格式一致
const emit = defineEmits(['change', 'update'])
(2)通过泛型
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
3、ref
import { ref, Ref } from 'vue'
const year = ref<string | number>('2020')
const el = ref<HTMLInputElement | null>(null)
const year: Ref<string | number> = ref('2020')
获取组件类型:
const modal = ref<InstanceType<typeof MyModal> | null>(null)
4、reactive
interface Book {
title: string
year?: number
}
const book: Book = reactive({ title: 'Vue 3 指引' })
5、computed
computed<number>(() => {
若返回值不是 number 类型则会报错
})
6、Provide、Inject
import { provide, inject, InjectionKey } from 'vue'
const key = Symbol() as InjectionKey<string>
provide(key, 'foo')
const foo = inject<string>('foo')
const foo = inject('foo') as string
</script>
|