我有一个简单的打字稿组件类,需要一个道具:
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());
}
}
我想在另一个打字稿组件类中初始化该类以获得特定的实例变量:
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>)
在不同情况下,此代码无需道具即可完美地适合我。但是我无法通过传递道具来解决这个问题。我该怎么办?
编辑:
通过这样的道具也不起作用:
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>>>>;
答案 0 :(得分:2)
一种解决方案是设置默认值:
@Prop({type: String, required: true, default: 'foo'}) readonly name!: string;
但是,在上面的示例中,我认为您将需要:
const colors = new ColorsPallet({
propsData: {
name: 'foo'
}
})