From 4a7abfbe03b0896ce3d606904c40bb4c89186ac3 Mon Sep 17 00:00:00 2001 From: jinzhan Date: Tue, 10 Aug 2021 18:59:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=B8=BAcomputed=E5=B1=9E=E6=80=A7?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0getter=E5=92=8Csetter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/runtime/data.js | 16 ++++++++++++++++ src/view/component.js | 12 ++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/runtime/data.js b/src/runtime/data.js index 40cb8dda..1589ed9a 100644 --- a/src/runtime/data.js +++ b/src/runtime/data.js @@ -177,6 +177,17 @@ function immutableSet(source, exprPaths, pathsStart, pathsLen, value, data) { return result; } +/** + * 检查是否是在更新computed的数据 + * + * @param {string} prop 数据项路径 + * @param {*} value 数据值 + * @return {boolean} 是否执行了computed的setter + */ + Data.prototype._updateComputed = function (prop, value) { + return this.__computed && this.__computed[prop] && (this.__computed[prop](value) || 1); +}; + /** * 设置数据项 * @@ -210,6 +221,11 @@ Data.prototype.set = function (expr, value, option) { }; var prop = expr.paths[0].value; + + if (!option.__forceComputed && this._updateComputed(prop, value)) { + return; + } + this.raw[prop] = immutableSet(this.raw[prop], expr.paths, 1, expr.paths.length, value, this); this.fire({ diff --git a/src/view/component.js b/src/view/component.js index c8385e09..01f60f45 100644 --- a/src/view/component.js +++ b/src/view/component.js @@ -491,7 +491,7 @@ Component.prototype._calcComputed = function (computedExpr) { var me = this; try { - var result = this.computed[computedExpr].call({ + var result = (this.computed[computedExpr].get || this.computed[computedExpr]).call({ data: { get: function (expr) { // #[begin] error @@ -516,11 +516,19 @@ Component.prototype._calcComputed = function (computedExpr) { } } }); - this.data.set(computedExpr, result); + this.data.set(computedExpr, result, { + // 添加一个flag,避免死循环 + __forceComputed: 1 + }); } catch (e) { handleError(e, this, 'computed:' + computedExpr); } + // 如果computed是对象且存在set方法 + if (this.computed[computedExpr].set) { + this.data.__computed = this.data.__computed || {}; + this.data.__computed[computedExpr] = bind(this.computed[computedExpr].set, this); + } }; /**