助力软件开发企业降本增效 PHP / java源码系统,只需一次付费,代码终身使用! 广告
[TOC] ## 概述 需要提前声明 ``` <script setup lang="ts"> ``` ## ref() 对简单类型可进行类型推导 ``` // 推导出的类型:Ref<number> const year = ref(2020) // => TS Error: Type 'string' is not assignable to type 'number'. year.value = '2020' ``` 声明 ``` // 得到的类型:Ref<string | number> const year = ref<string | number>('2020') year.value = 2020 // 成功! ``` 如果声明时,没有指定默认值,会得到一个包含 undefined 的联合类型 ``` // 推导得到的类型:Ref<number | undefined> const n = ref<number>() ``` ## reactive() reactive() 也会隐式地从它的参数中推导类型: ``` import { reactive } from 'vue' // 推导得到的类型:{ title: string } const book = reactive({ title: 'Vue 3 指引' }) ``` 要显式地标注一个 reactive 变量的类型,我们可以使用接口: ``` import { reactive } from 'vue' interface Book { title: string year?: number } const book: Book = reactive({ title: 'Vue 3 指引' }) ``` ## computed() computed 可通过类型推导出类型 显示声明 ``` const double = computed<number>(() => { // 若返回值不是 number 类型则会报错 }) ``` ## props 对比 运行时的,类型声明 ``` <script setup lang="ts"> const props = defineProps({ foo: { type: String, required: true }, bar: Number }) props.foo // string props.bar // number | undefined </script> ``` Ts的类型声明 方式一 ``` <script setup lang="ts"> const props = defineProps<{ foo: string bar?: number }>() </script> ``` 方式二: ``` interface Props { foo: string bar?: number } const props \= defineProps() ``` 使用 声明试如果需要添加默认值 使用如下方式 ``` export interface Props { msg?: string labels?: string[] } const props = withDefaults(defineProps<Props>(), { msg: 'hello', labels: () => ['one', 'two'] }) ``` ## 子组件的 emits ``` <script setup lang="ts"> // 运行时 const emit = defineEmits(['change', 'update']) // 基于类型 const emit = defineEmits<{ (e: 'change', id: number): void (e: 'update', value: string): void }>() </script> ```