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

标签 javascript typescript vue.js vuejs3

我已经在 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/

相关文章:

typescript - 在 TypeScript 中切换特定类型

angular - Scheduler.async 的 RxJS 依赖问题

typescript - 是否可以在 Visual Studio 2015 中配置 TSLint?

javascript - Vue.js Avoriaz 单元测试在使用 vue-i18n 时产生翻译警告

javascript - 从 onChange 输入元素中调用的函数获取索引值

JavaScript上下箭头菜单(仅限Javascript)

javascript - 单击 Vuetify 3 后如何取消对按钮的聚焦

javascript - 更新 Watch Vue.js 上的 cookie

Javascript 将数据放入列表中

javascript - 如果你添加一个类似 facebook 的按钮,定时器每 100 毫秒触发一次