如何在 Vue3 组件中使用 TS 类型(必看)

一、为 props 标注类型

使用 <script setup>

方式一:当使用 <script setup> 时,defineProps() 宏函数支持从它的参数中推导类型:

const props = defineProps({
      treeTableProps: {
            type: Array,
            default: null,
            required: false
      },
      msg: {
            type: String,
            required: false
      }

})
// 使用
console.log(props.msg)

方式二:通过泛型参数来定义 props 的类型,这种方式更加直接

interface T {
      prop: string,
      label: string,
      width: number,
      children: Array<T>
}
const props = defineProps<{
      msg?: string,
      treeTableProps: Array<T>,
}>()

猜你喜欢

转载自blog.csdn.net/qq_41579104/article/details/131247903
今日推荐