javascript - Vue 3 + typescript:单个文件组件中的类型检查道具
问题描述
我在 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 类型有什么意义?
解决方案
根据Typescript 支持文档,这就type:String
足够了,如果需要,您可以添加验证器:
export default defineComponent({
props: {
label: {
type: String ,
default: ''
},
},
});
你也可以这样做:
export default defineComponent({
props: {
label: {
type: String as PropType<string>,
default: ''
},
},
});
我认为您使用的语法是用于函数检查类型。
推荐阅读
- google-play-console - Google Play 安装量减去卸载量是否应该与有效安装量相匹配?
- css - 如何以表格的形式在屏幕上设置我的 json 数据样式?
- javascript - 使用 gitignore 隐藏文件
- ubuntu-18.04 - ROS2 Eloquent 安装在 Ubuntu 18.04.4 LTS 中失败
- sql - 使用 BETWEEN 函数
- mysql - 在 MYSQL 中查找利润最大的月份
- javascript - 如何使用 Mutation 观察者而不是 settimeout 来附加 div
- javascript - Highcharts - 是否可以为特定区域应用不透明度?
- c++ - 为什么我得到这个随机的奇怪数字 C++
- angular - Angular:托管在firebase上的网站无法登录