【问题标题】:Vue 3 + typescript : type check props in single file componentVue 3 + typescript:单个文件组件中的类型检查道具
【发布时间】:2021-02-01 15:20:57
【问题描述】:

我在 Vuetify 和其他地方看到了可以在模板标签中为 prop 添加类型检查的地方。

假设我们有一个按钮组件

<template>
    <div>
        <button>{{ label }}</button>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
    props: {
        label: { type: String as () => string, default: '' },
    },
});
</script>

现在在父组件中:

<button-component :label="true" />

我会从 Vue 本身得到一个编译器警告它是错误的参数,但是可以在输入代码时检查吗?如果不是,在 props 中指定 ts 类型有什么意义?

【问题讨论】:

标签: javascript typescript vue.js vuejs3


【解决方案1】:

基于Typescript support docs type:String 就足够了,如果需要,您可以添加验证器:

export default defineComponent({
    props: {
        label: { 
          type: String ,
          default: ''
          },
    },
});

你也可以这样做:

export default defineComponent({
    props: {
        label: {
          type: String as PropType<string>,
          default: ''
          },
    },
});

我认为您使用的语法是用于函数检查类型。

【讨论】:

    【解决方案2】:

    如果您想提交 String,而不是布尔值,您可以执行以下操作:

    <button-component :label="`true`" />
    

    因为您正在绑定,所以 vue 编译器会将您的真实值转换为布尔值。所以在这里明确定义一个字符串输入。

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 2019-01-29
      • 2018-08-20
      • 2018-12-10
      • 2019-07-27
      • 1970-01-01
      • 2018-10-09
      • 2021-05-31
      相关资源
      最近更新 更多