【问题标题】:How to manually define props type in vue3 with typescript如何使用 typescript 在 vue3 中手动定义 props 类型
【发布时间】:2023-03-15 15:00:02
【问题描述】:

我可以的

defineComponent({
  props: {
    name: { type: String as PropType<string> }
  }
})

告诉 vue3 我的 props 类型是 { name: string },但是如果我有几个组件具有相同的 props 类型,我该如何共享定义?

如果我在 :

中定义道具
const props = {
  name: String as PropType<string>
}

然后像这样使用它:

defineComponent({
  props: props,
})

不行,我在props的setup函数中得到的类型不对。

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    defineComponent 提供的 props 选项是一个纯 js 对象,仅用于类型注释目的,因此您可以使用 javascript 中的任何技术在对象之间共享结构:

    // in common.ts
    export const commonProps = {
      name: { type: String as PropType<string> }
    }
    
    // in your component.vue
    import commonProps from "./common.ts";
    
    defineComponent({
      props:{
        ...commonProps,
    
        extra: { }
    
      }
    })
    
    

    【讨论】:

      【解决方案2】:

      如果您将组合 API 与 Vue 2 一起使用以准备切换到 Vue 3,则必须使用该包中的 PropType 而不是 vue 包。

      // Wrong for Vue 2
      import Vue, { PropType } from 'vue'
      import { defineComponent } from '@vue/composition-api'
      
      // Right for Vue 2
      import { defineComponent, PropType } from '@vue/composition-api'
      

      【讨论】:

      • 这不是问题,作者明确写了“Vue3”而不是“Vue2”
      猜你喜欢
      • 2021-10-11
      • 2021-10-14
      • 2021-05-28
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2018-02-23
      相关资源
      最近更新 更多