Skip to content

Instantly share code, notes, and snippets.

@wtho
Last active October 12, 2020 08:21
Show Gist options
  • Save wtho/86143a3a37e90aad7801c2dd7f9a11a3 to your computer and use it in GitHub Desktop.
Save wtho/86143a3a37e90aad7801c2dd7f9a11a3 to your computer and use it in GitHub Desktop.
v3.vuejs.decorators
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