1.父子传参,props以及emits的标注类型
当使用<script setup lang="ts"></script>
通过父组件进行传参,然后在子组件中通过‘运行声明’的方式进行接收参数
<script setup lang="ts">
const props = defineProps({
dataValue: { type: String, required: true },
barValue: Number
})
</script>
当在非<script setup lang="ts"></script>的情况下
用defineComponent()先从props选项中推导出来,然后将props传入到setup(props){}函数中
import { defineComponent } from 'vue'
export default defineComponent({
props: {
message: String
},
setup(props) {
props.message // <-- 类型:string
}
})
为 组件emits添加标注类型
在 <script setup>
中,emit
函数的类型标注
<script setup lang="ts">
//第一种 运行时
const emit = defineEmits(['change', 'update'])
//第二种 基于类型
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
</script>
不在<script setup>的场景下
import { defineComponent } from 'vue'
export default defineComponent({
emits: ['change'],
setup(props, { emit }) {
emit('change') // <-- 类型检查 / 自动补全
}
})
2.为ref()和reactive()中添加标注类型
对于基本数据类型就用ref()
// 得到的类型:Ref<string | number> <>中可以添加都可能的数据类型作为泛型
const year = ref<string | number>('2020')
year.value = 2020
对于复杂类型的数据优先使用reactive()
reactive()
也会隐式地从它的参数中推导类型:
import { reactive } from 'vue'
// 推导得到的类型:{ title: string }
const book = reactive({ title: '前端学习信息' })
要显示标注类型,可以使用接口
import { reactive } from 'vue'
interface Book {
title: string
year?: number
}
const book: Book = reactive({ title: '前端学习信息' })
3.computed标注类型
computed()
会自动从其计算函数的返回值上推导出类型:
import { ref, computed } from 'vue'
const count = ref(0)
// 推导得到的类型:ComputedRef<number>
const double = computed(() => count.value * 2)
// => TS Error: Property 'split' does not exist on type 'number'
const result = double.value.split('')
也可以通过泛型显示指定类型
const double = computed<number>(() => {
// 若返回值不是 number 类型则会报错
})
4.为事件处理函数准备标注类型
默认情况下是隐式转换成any,如下是显示转换
function handleChange(event: Event) {
console.log((event.target as HTMLInputElement).value)
}