将 VueJS Prop 传递给 TypeScript 类组件
Posted
技术标签:
【中文标题】将 VueJS Prop 传递给 TypeScript 类组件【英文标题】:Passing VueJS Prop into TypeScript class component 【发布时间】:2020-05-22 23:43:03 【问题描述】:我有一个简单的打字稿组件类,需要一个道具:
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>>>>;
【问题讨论】:
离题,但考虑到 TS 类组合已从 2.6.x 中弃用 【参考方案1】:一种解决方案是设置默认值:
@Prop(type: String, required: true, default: 'foo') readonly name!: string;
但是,在您上面的示例中,我相信您需要:
const colors = new ColorsPallet(
propsData:
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'.
嗯...我从来没有将道具传递给组件构造函数,我会更新。
可能值得只做默认值
是的,您的回答进展顺利,我会稍微更新一下我的问题,以便更具体地解决问题的核心。
我可以明确地设置一个默认值,然后设置名称。但是,我仍然相信它可以一步完成。你怎么看?以上是关于将 VueJS Prop 传递给 TypeScript 类组件的主要内容,如果未能解决你的问题,请参考以下文章