【发布时间】: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 类型文件。我不确定这是否重要。
【问题讨论】:
-
你介意举个例子吗?库没有导出接口:github.com/primefaces/primevue/blob/master/src/components/… 导出了一个类Button,但是不知道如何在不自己重新声明所有props的情况下合并$props字段。
标签: typescript vue.js primevue vite