问题描述
假设我有这个输入组件:
$dsn = 'pgsql:host=postgres-service;port=5432;dbname=db_my_test_app';
现在,我像这样使用这个组件并提供 import { defineComponent } from "@vue/runtime-core"
export default defineComponent({
inheritAttrs: false,setup(props,{ attrs }) {
return () => (
<div>
<input type="text" {...attrs} />
</div>
)
}
})
属性:
type="password"
但打字稿抱怨:
import { defineComponent } from "@vue/runtime-core"
import Input from "./components/input"
export default defineComponent({
setup(props,{ attrs }) {
return () => <Input type="password"></Input>
}
})
解决方法
所以我不是 Vue.JS 专家(请告诉我它是否不起作用以及为什么),但经过一些研究我发现您必须通过添加 {{1} 来键入 props
}} 对象到 props
。这将告诉 TypeScript 你可以传递特定的 props。
defineComponent
您可能会问 import { defineComponent } from "@vue/runtime-core"
export default defineComponent({
inheritAttrs: false,props: {
type: String // this is the typing (warning: you cannot use typescript types here)
}
setup(props,{ attrs }) {
return () => (
<div>
<input type={props.type ?? "text"} {...attrs} />
</div>
)
}
})
运算符的作用。我喜欢称它为“默认操作符”,因为它默认了它之前的值和它之后的值。在这种情况下,这意味着如果 ??
是 props.type
或 undefined
,它将用 null
替换它。