我有一个简单的 typescript 组件类,需要一个 Prop :
export default class ColorsPallet extends Vue {
@Prop({type: String, required: true}) readonly name!: string;
private readonly view: StorageItem;
private readonly stored: StorageItem;
private readonly colors: ColorItems;
constructor() {
super();
this.colors = db.colors[this.name]['items'];
this.storedColor = new StorageItem(this.name + '-stored-color', localStorage, db.colors[this.name]['default']);
this.viewColor = new StorageItem(this.name + '-view-color', sessionStorage, this.storedColor.get());
}
}
我希望在不同的 typescript 组件类中初始化此类以获取特定的实例变量:
constructor() {
super();
const colors = new ColorsPallet();
console.log(color.$data.viewColor.get());
}
这给了我一个明显的错误:
[Vue warn]: Missing required prop: "name"
(found in <Root>)
所以我将初始化更改为:
const colors = new ColorsPallet({props: ['name']})
这仍然给我一个类型错误,因为我没有真正传递任何东西:
[Vue warn]: Error in data(): "TypeError: Cannot read property 'items' of undefined"
(found in <Root>)
无需 Prop ,此代码在不同情况下都可以完美地工作。然而,我无法通过传递 Prop 来实现这一点。我该怎么办?
编辑:
像这样传递 prop 也不起作用:
const colors = new ColorsPallet({
name: 'foo'
})
导致此错误的结果:
TS2345: Argument of type '{ props: { name: string; }; }' is not assignable to parameter of type 'ComponentOptions<Vue, DefaultData<Vue>, DefaultMethods<Vue>, DefaultComputed, PropsDefinition<Record<string, any>>, Record<string, any>>'. Types of property 'props' are incompatible. Type '{ name: string; }' is not assignable to type 'string[] | RecordPropsDefinition<Record<string, any>> | undefined'. Type '{ name: string; }' is not assignable to type 'undefined'.
所需格式的类型:
/**
* This type should be used when an array of strings is used for a component's `props` value.
*/
export type ThisTypedComponentOptionsWithArrayProps<V extends Vue, Data, Methods, Computed, PropNames extends string> =
object &
ComponentOptions<V, DataDef<Data, Record<PropNames, any>, V>, Methods, Computed, PropNames[], Record<PropNames, any>> &
ThisType<CombinedVueInstance<V, Data, Methods, Computed, Readonly<Record<PropNames, any>>>>;
最佳答案
一种解决方案是设置默认值:
@Prop({type: String, required: true, default: 'foo'}) readonly name!: string;
但是,在上面的示例中,我相信您需要:
const colors = new ColorsPallet({
propsData: {
name: 'foo'
}
})
关于javascript - 将 VueJS Prop 传递到 TypeScript 类组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60103250/