Skip to content

Instantly share code, notes, and snippets.

@yotamofek
Created February 14, 2019 09:48
Show Gist options
  • Save yotamofek/2ad8fd67af4ba00458fe1eaac30d7011 to your computer and use it in GitHub Desktop.
Save yotamofek/2ad8fd67af4ba00458fe1eaac30d7011 to your computer and use it in GitHub Desktop.
export { default as Vue } from 'vue'
export { mixins } from 'vue-class-component'
import $Component from 'vue-class-component'
import { Prop as $Prop, Watch as $Watch } from 'vue-property-decorator'
const isDescriptor = obj => obj?.[Symbol.toStringTag] === 'Descriptor'
export function Prop (...options) {
const decorator = fieldDescriptor => {
if (fieldDescriptor.initializer) {
(options = options.length === 0 ? [{}] : options)[0].default = fieldDescriptor.initializer()
fieldDescriptor.initializer = undefined
}
return {
...fieldDescriptor,
finisher: klass => {
$Prop(...options)(klass, fieldDescriptor.key, fieldDescriptor.descriptor)
return klass
}
}
}
return isDescriptor(options[0])
? decorator(options.shift())
: decorator
}
export function Watch (...options) {
const decorator = fieldDescriptor => ({
...fieldDescriptor,
finisher: klass => {
$Watch(...options)(klass, fieldDescriptor.key, fieldDescriptor.descriptor)
return klass
}
})
return isDescriptor(options[0])
? decorator(options.shift())
: decorator
}
export function Component (options) {
const decorator = classDescriptor => ({
...classDescriptor,
finisher: klass => {
klass = $Component(options)(klass)
const undefinedDataFields = {}
for (const elementDescriptor of classDescriptor.elements) {
const isUndefinedDataField = (
elementDescriptor.kind === 'field' &&
elementDescriptor.initializer?.() === undefined &&
(klass.options.props === undefined || !(elementDescriptor.key in klass.options.props))
)
if (isUndefinedDataField) {
undefinedDataFields[elementDescriptor.key] = undefined
}
}
if (Object.getOwnPropertyNames(undefinedDataFields).length > 0) {
const { options } = klass
const { data } = options
options.data = function (...args) {
return data ? {
...this::data(...args),
...undefinedDataFields
} : undefinedDataFields
}
}
return klass
}
})
return isDescriptor(options)
? decorator(options)
: decorator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment