Last active
October 12, 2020 08:21
-
-
Save wtho/86143a3a37e90aad7801c2dd7f9a11a3 to your computer and use it in GitHub Desktop.
v3.vuejs.decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Options, Vue, createDecorator } from "vue-class-component"; | |
import { ComponentPropsOptions } from "vue"; | |
import 'reflect-metadata'; | |
type PropOptions = ComponentPropsOptions; | |
type Constructor = { | |
new(...args: any[]): any | |
} | |
const reflectMetadataIsSupported = | |
typeof Reflect !== 'undefined' && typeof Reflect.getMetadata !== 'undefined' | |
function applyMetadata( | |
options: PropOptions | Constructor[] | Constructor, | |
target: Vue, | |
key: string, | |
) { | |
if (reflectMetadataIsSupported) { | |
if ( | |
!Array.isArray(options) && | |
typeof options !== 'function' && | |
typeof options.type === 'undefined' | |
) { | |
const type = Reflect.getMetadata('design:type', target, key) | |
if (type !== Object) { | |
options.type = type | |
} | |
} | |
} | |
} | |
/** | |
* decorator of a prop | |
* @param options the options for the prop | |
* @return PropertyDecorator | void | |
*/ | |
export function Prop(options: PropOptions | Constructor[] | Constructor = {}) { | |
return (target: Vue, key: string) => { | |
applyMetadata(options, target, key) | |
createDecorator((componentOptions, k) => { | |
;(componentOptions.props || ((componentOptions.props = {}) as any))[ | |
k | |
] = options | |
})(target, key) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment