From ff740fb11bc2f501ef92370e9b9d837e8c7648cf Mon Sep 17 00:00:00 2001 From: chenzewang <809555918@qq.com> Date: Tue, 16 Jun 2020 11:06:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BB=A3=E7=90=86=E5=87=BD?= =?UTF-8?q?=E6=95=B0=5FproxyAttribbute=E3=80=82=E4=BB=A3=E7=90=86vm.$optio?= =?UTF-8?q?ns.methos=20=E5=88=B0vm=E4=B8=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/mvvm.js | 65 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 45 insertions(+), 20 deletions(-) diff --git a/js/mvvm.js b/js/mvvm.js index b37a2d55..4f9d6a86 100644 --- a/js/mvvm.js +++ b/js/mvvm.js @@ -5,10 +5,16 @@ function MVVM(options) { // 数据代理 // 实现 vm.xxx -> vm._data.xxx - Object.keys(data).forEach(function(key) { + Object.keys(data).forEach(function (key) { me._proxyData(key); }); + // 代理methods + // 实现 vm.xxx -> vm.options.methods.xxx + Object.keys(me.$options.methods).forEach(function (key) { + me._proxyAttribute(key, me.$options.methods, me) + }); + this._initComputed(); observe(data, this); @@ -18,35 +24,54 @@ function MVVM(options) { MVVM.prototype = { constructor: MVVM, - $watch: function(key, cb, options) { + $watch: function (key, cb, options) { new Watcher(this, key, cb); }, - _proxyData: function(key, setter, getter) { + _proxyData: function (key, setter, getter) { var me = this; - setter = setter || - Object.defineProperty(me, key, { - configurable: false, - enumerable: true, - get: function proxyGetter() { - return me._data[key]; - }, - set: function proxySetter(newVal) { - me._data[key] = newVal; - } - }); + setter = setter || + Object.defineProperty(me, key, { + configurable: false, + enumerable: true, + get: function proxyGetter() { + return me._data[key]; + }, + set: function proxySetter(newVal) { + me._data[key] = newVal; + } + }); }, - _initComputed: function() { + /** + * + * @param {*} key source的一个要被代理的属性名 + * @param {*} source source的各个属性被代理到target + * @param {*} target target[key] 可以访问到source[key] + */ + _proxyAttribute: function (key, source, target) { + Object.defineProperty(target, key, { + configurable: false, + enumerable: false, + get: function proxyGetter() { + return source[key]; + }, + set: function proxySetter(newVal) { + source[key] = newVal; + } + }); + }, + + _initComputed: function () { var me = this; var computed = this.$options.computed; if (typeof computed === 'object') { - Object.keys(computed).forEach(function(key) { + Object.keys(computed).forEach(function (key) { Object.defineProperty(me, key, { - get: typeof computed[key] === 'function' - ? computed[key] - : computed[key].get, - set: function() {} + get: typeof computed[key] === 'function' ? + computed[key] : + computed[key].get, + set: function () {} }); }); }