Skip to content

Instantly share code, notes, and snippets.

@davestewart
Last active May 12, 2020 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davestewart/1f8509ca17839e055485a160fea15ea3 to your computer and use it in GitHub Desktop.
Save davestewart/1f8509ca17839e055485a160fea15ea3 to your computer and use it in GitHub Desktop.
TypeScript decorator to add Vue computed getters to a TypeScript class
import Vue from 'vue'
export function cached (target: Function) {
// get descriptors
const descriptors: any = Object.getOwnPropertyDescriptors(target.prototype)
const getters = Object
.keys(descriptors)
.filter(key => descriptors[key].get && !descriptors[key].set)
// we have getters!
if (getters.length) {
// scope for accessors
let scope = null
// build caching layer
const cache = new Vue({
computed: getters.reduce((output, key) => {
// cache reference to original accessors
const { get } = descriptors[key]
// create getter
output[key] = () => get.call(scope)
return output
}, {})
})
// update descriptors
getters.forEach(key => {
const descriptor = descriptors[key]
descriptor.get = function () {
scope = this
return cache[key]
}
// update original descriptor
Object.defineProperty(target.prototype, key, descriptor)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment