【问题标题】:Vue 3 - Extend a Vue component with additional props with Typescript supportVue 3 - 使用带有 Typescript 支持的附加道具扩展 Vue 组件
【发布时间】:2021-05-31 18:14:47
【问题描述】:

我正在尝试扩展第 3 方 Vue 组件(来自 PrimeVue)并添加其他道具,但我想保留原始组件的类型并将它们与我的其他道具结合。

例如,使用下面的第 3 方 Button 组件,其类型强制“标签”必须是字符串,如果我尝试传递数字,我的 IDE(VSCode + Vetur)会将其标记为错误。

如果我将 Button 类扩展为我自己的组件 BaseButton,使用下面的通用模式,我将能够将数字或任何其他类型传递给 label 属性,而 IDE 不会报错。除了维护原始 Button 组件的类型之外,我还想将它与我的其他道具结合起来,例如myProp: string 下方。

<template>
  <Button v-bind="$attrs" :label="myComputedLabel">
    <template v-for="(_, slot) of $slots" v-slot:[slot]="scope">
      <slot :name="slot" v-bind="scope"/>
    </template>
  </Button>
</template>

<script>
  export default defineComponent({
  name: 'BaseButton',
  props: {
    myProp: {
      type: String
    }
  },
  setup(props) {
    const myComputedLabel = computed(() => {
      return `Hello ${props.myProp}`;
    });
  }
 })
</script>

在我的例子中,第 3 方组件是用 Vue 和 vanilla JS 编写的,但有一个外部 Button.d.ts 类型文件。我不确定这是否重要。

【问题讨论】:

标签: typescript vue.js primevue vite


【解决方案1】:

您可以从组件的setup 选项中读取它,propssetup 的第一个参数

type MyButtonProp = Parameters<NonNullable<typeof Button.setup>>[0]

简单地说,这是一个通用类型

type ComponentProps<T extends { setup?: any }> = Parameters<NonNullable<T['setup']>>[0]

用法

type MyButtonProp = ComponentProps<typeof Button>

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2022-06-16
    • 2020-01-09
    • 2021-07-11
    • 2020-04-06
    • 2021-10-25
    • 2023-03-20
    • 2018-12-10
    • 2021-02-01
    相关资源
    最近更新 更多