Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Created October 7, 2017 21:56
Show Gist options
  • Save yyx990803/8d06cd02022d1b37f3fbc588843b388c to your computer and use it in GitHub Desktop.
Save yyx990803/8d06cd02022d1b37f3fbc588843b388c to your computer and use it in GitHub Desktop.
An idea of using a babel plugin to translate a class into a Vue component.
// component decorator is required
@component
// `name` and `extends` options inferred from class signature
class Foo extends Bar {
// options can be specified as a static property
static template = `
<div>{{ foo }}</div>
`;
static components = {
MyComponent
};
static mixins = [SomeMixin];
// props
@prop someProp
@prop({
type: String,
required: true
})
foo = 'default value'
// reactive data
msg = 'hello'
bar = 123
// non-reactive properties (for complex external objects)
@nonReactive vector = new Three.Vector()
// provide/inject
@provide some = 1
@inject foo
@inject('dur') bar // inject as bar from dur
@inject baz = 123 // inject with default value
// watch
@watch('foo') onFooChanged (newVal, oldVal) {}
@watch(vm => vm.a + vm.b, { deep: true }) onChange (newVal, oldVal) {
}
// computed
// Why not getters? Because getters have the semantics of re-computing on
// every access, while Vue computed properties have caching behavior.
@computed foo () {
return 123
}
// also allows smoother syntax with initialzer
@computed bar = vm => vm.a + 1
// getters indicates... well, just a getter, with no caching.
get baz () {
return this.a + 1
}
// the above's equivalent
@computed({ cache: false }) baz = vm => vm.a + 1
// hooks
// Why not just infer it? Because infering requires the plugin to keep a copy
// of built-in hooks which may change in newer versions of Vue core.
@hook created () {}
@hook destroyed () {}
@hook errorCaptured () {}
// methods
greet () {
}
}
  • Implemented as a babel plugin. This avoids the runtime cost of vue-class-component (expensive data collection workaround)
  • Can avoid having to import every single decorator because they are compiled away
  • Maybe hard to make work with TS?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment