Vue3中如何导出计算属性类型用于子组件Props定义?
Vue3 + TypeScript 导出计算属性类型给子组件的解决方案
针对你遇到的问题,这里有几个实用的方案,不用手动重复定义复杂类型:
方案1:直接在<script setup>导出类型(Vue3.3+)
Vue 3.3及以上版本支持在<script setup>里直接导出类型,你可以通过typeof获取计算属性值的类型,然后导出给子组件使用:
// Parent.vue <script setup lang="ts"> const { results } = useQuery(...) const myComputed = computed(() => results.nested.item.is.here) // 导出计算属性对应的值类型 export type PassToMeType = typeof myComputed.value </script> <template> <Child :passToMe="myComputed" /> </template>
子组件直接导入这个类型即可:
// Child.vue <script setup lang="ts"> import type { PassToMeType } from './Parent.vue' const props = defineProps<{ passToMe: PassToMeType }>() </script>
方案2:兼容旧版本Vue的类型导出
如果你的Vue版本低于3.3,没法直接在<script setup>导出类型,可以通过defineExpose暴露计算属性,再在独立的<script>标签里提取并导出类型:
// Parent.vue <script setup lang="ts"> const { results } = useQuery(...) const myComputed = computed(() => results.nested.item.is.here) // 把计算属性暴露给外部脚本 defineExpose({ myComputed }) </script> <!-- 独立脚本标签处理类型导出 --> <script lang="ts"> import type { ComponentInternalInstance } from 'vue' // 获取父组件实例的类型,提取myComputed的值类型 type ParentInstance = InstanceType<typeof import('./Parent.vue').default> export type PassToMeType = ParentInstance['myComputed']['value'] </script> <template> <Child :passToMe="myComputed" /> </template>
子组件同样导入PassToMeType使用即可。
方案3:提前提取嵌套值的类型
你也可以先从GraphQL返回结果里提取目标嵌套值的类型,再用这个类型约束计算属性,同时导出:
// Parent.vue <script setup lang="ts"> const { results } = useQuery(...) // 直接从results里提取嵌套值的类型 export type PassToMeType = typeof results.nested.item.is.here // 用提取的类型约束计算属性(可选,提升编辑器提示) const myComputed = computed<PassToMeType>(() => results.nested.item.is.here) </script> <template> <Child :passToMe="myComputed" /> </template>
这个方案不依赖Vue版本,只要TypeScript环境支持就能用。
内容的提问来源于stack exchange,提问作者Jtcruthers
相关产品推荐
相关产品推荐

