相信大家的项目都已经接入了typescript,如果还没有接入的希望大家尽早接入。如果是用vuejs2.x的小伙伴,一定对vue-property-decorator 模块不陌生,我们经常在项目里这么用:
import { Vue, Component, Prop, Provide, Inject } from 'vue-property-decorator';
我们知道在vuejs原生语法里,provide、inject是配对使用的,在装饰器语法里@Provide,@Inject装饰器也需要配对使用,存在下面这种场景:
childrenB组卷的Inject就是可选参数,我们如何来设置呢?正确姿势如下:
@Inject({
from: 'setFileIdentifier',
default: () => {
return undefined
}
})
setFileIdentifier?: Function;
我们可以来看下Inject的声明文件:
declare type InjectOptions = {
from?: InjectKey;
default?: any;
};
/**
* decorator of an inject
* @param from key
* @return PropertyDecorator
*/
export declare function Inject(options?: InjectOptions | InjectKey): import("vue-class-component").VueDecorator;
说明Inject是支持两种类型参数的InjectOptions和InjectKey
declare type InjectOptions = {
from?: InjectKey;
default?: any;
};
export type InjectKey = string | symbol;
这里有个default参数,我们可以利用这个参数返回一个undefined,在使用地方做个判断,例如:
this.setFileIdentifier ? this.setFileIdentifier() : this.entityIdentifier()