Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
VueJS - Implementing Computed Property - Part One
const Watcher = require('./watcher');
const noop = function () {};
const sharedPropDef = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function initComputed(vm, computed) {
vm._computedWatchers = Object.create(null);
for (const key in computed) {
value = computed[key];
vm._computedWatchers[key] = new Watcher(vm, value);
if (!(key in vm)) {
sharedPropDef.set = noop;
sharedPropDef.get = function () {
const watcher = vm._computedWatchers && vm._computedWatchers[key];
if (watcher) return watcher.value;
};
Object.defineProperty(vm, key, sharedPropDef);
} // if
} // for
}
//////////////////
function myVue(opts) {
this._data = opts.data;
Object
.keys(opts.data)
.forEach(key => {
sharedPropDef.get = () => this._data[key];
sharedPropDef.set = (val) => { this._data[key] = val; };
Object.defineProperty(this, key, sharedPropDef);
});
if (opts.computed) initComputed(this, opts.computed);
}
//////////////////
data = { msg: 'hello' };
computed = {
reversedMsg() {
console.log('reversed...');
return this.msg.split('').reverse().join('');
},
upperCased() {
console.log('uppercased...');
return this.msg.toUpperCase();
}
};
opts = { data, computed };
vm = new myVue(opts);
console.log(vm.reversedMsg);
console.log(vm.reversedMsg);
console.log(vm.upperCased);
console.log(vm.upperCased);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment