vue3组合式 API_为 computed() 标注类型

发布时间 2023-07-21 15:21:58作者: 商品部-林军

image-20230131102803448

computed() 会自动从其计算函数的返回值上推导出类型

<template>
 <h3>{{ doubleCount }}</h3>
</template>

<script setup lang="ts">
import { ref,computed } from "vue"
const count = ref<number>(100)
// 推导得到的类型:ComputedRef<number>
const doubleCount = computed(() => count.value * 2)
// Property 'split' does not exist on type 'number'
const result = doubleCount.value.split('');
</script>

你还可以通过泛型参数显式指定类型

<template>
 <h3>{{ doubleCount }}</h3>
</template>

<script setup lang="ts">
import { ref,computed } from "vue"
const count = ref<number>(100)
const doubleCount = computed<number>(() => {
 // 若返回值不是 number 类型则会报错
 return count.value * 2
})
</script>