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

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>

 

posted @ 2023-07-21 15:16  商品部-林军  阅读(202)  评论(0编辑  收藏  举报