繁体   English   中英

Vue 3 + 打字稿:在单个文件组件中键入检查道具

[英]Vue 3 + typescript : type check props in single file component

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

假设我们有一个按钮组件

<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 类型有什么意义?

根据Typescript 支持文档type:String就足够了,如果需要,您可以添加验证器:

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

你也可以这样做:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM