0

我有一个简单的打字稿组件类,需要一个道具:

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>>>>;
4

1 回答 1

2

一种解决方案是设置默认值:

@Prop({type: String, required: true, default: 'foo'}) readonly name!: string;

但是,在您上面的示例中,我相信您需要:

const colors = new ColorsPallet({
  propsData: {
    name: 'foo'
  }
})
于 2020-02-06T21:00:20.190 回答