【问题标题】:Strongly typing props of vue components using composition api and typescript typing system使用组合 api 和 typescript 类型系统强类型化 vue 组件的 props
【发布时间】:2020-05-14 21:49:42
【问题描述】:

我正在使用带有 typescript 的 vue composition api。

如何使用打字稿打字系统强输入组件道具?

【问题讨论】:

    标签: typescript vue.js strong-typing vue-composition-api


    【解决方案1】:

    Troy Kessier 的回答并不完全准确。我引用the documentation on definecomponent

    或者,如果您的组件不使用除 setup 本身以外的任何选项,您可以直接传递函数 […]

    所以没有两种声明属性的方式,而是两种声明组件的方式,并且每种方式都提供了自己的 props 类型。

    使用经典方式和TypeScript,使用PropType

    import { defineComponent, PropType } from 'vue'
    
    export default defineComponent({
      props: {
        someOptionalString: String,
    
        someRequiredString: {
          type: String,
          required: true
        },
    
        someObject: {
          type: Object as PropType<MyObjectType>,
          required: true
        },
      },
    
      // …
    })
    

    注意:PropType 有助于为 setup 函数中的 props 参数提供正确的 TypeScript 类型。但是 props 的底层 Vue 类型仍然是 Object,目前没有办法为父组件传递的这些 props 强制执行更好的类型。

    【讨论】:

    • 我试过这个但它对我不起作用,如果我传入 { foo: 'bar' } 它不会抱怨,换句话说它只是检查父组件是否正在传递一个对象,而不是如果它与我的自定义类型的数据结构匹配。我在 .vue 脚本标签中使用 lang="ts" ,TypeScript 在 .ts 文件中正常工作,而且我的类型在 Vuex 中运行良好。
    • @LeeComstock 当然可以。我编辑了。让我知道现在是否清楚。
    • 完美运行!谢谢!
    • 拉了几个小时的头发后救了我,谢谢!
    • 那些不是打字稿打字。
    【解决方案2】:

    正如官方docs 中解释的那样,您可以通过两种方式输入道具:

    通过参数注释定义 arops

    import { defineComponent } from 'vue'
    
    export default defineComponent((props: { foo: string }) => {
      props.foo
    })
    

    或者像这样

    import { defineComponent } from 'vue'
    
    export default defineComponent({
      props: {
        foo: String
      },
      setup(props) {
        props.foo // <- type: string
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2012-10-03
      • 2020-07-27
      • 2020-10-24
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      相关资源
      最近更新 更多