gpt4 book ai didi

javascript - Vue 3 + typescript : type check props in single file component

转载 作者:行者123 更新时间:2023-12-03 06:41:11 24 4
gpt4 key购买 nike

我已经在 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 support docs type:String就足够了,如果需要,您可以添加验证器:

export default defineComponent({
props: {
label: {
type: String ,
default: ''
},
},
});
你也可以这样做:
export default defineComponent({
props: {
label: {
type: String as PropType<string>,
default: ''
},
},
});
我认为您使用的语法用于函数检查类型。

关于javascript - Vue 3 + typescript : type check props in single file component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64417343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com