蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 核验计算属性依赖缓存、methods 重复求值及 computed setter 反向更新

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-vue-computed.py
explore-vue-computed.py310 行
"""Offline Playwright Chromium lab for Vue 2 Chapter 08 (vue-computed)."""
import json
from playwright.sync_api import sync_playwright

MINI_VUE2_COMPUTED_JS = r"""
(function (global) {
  class Dep {
    constructor() { this.subs = new Set(); }
    depend() { if (Dep.target) this.subs.add(Dep.target); }
    notify() { Array.from(this.subs).forEach(w => w.update()); }
  }
  Dep.target = null;
  const targetStack = [];
  function pushTarget(t) { targetStack.push(t); Dep.target = t; }
  function popTarget() { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1] || null; }

  class Watcher {
    constructor(vm, getter, cb, options) {
      this.vm = vm;
      this.getter = getter;
      this.cb = cb;
      this.lazy = Boolean(options && options.lazy);
      this.dirty = this.lazy;
      this.deps = new Set();
      this.dep = this.lazy ? new Dep() : null;
      this.value = this.lazy ? undefined : this.get();
    }
    get() {
      pushTarget(this);
      const val = this.getter.call(this.vm);
      popTarget();
      return val;
    }
    evaluate() {
      this.value = this.get();
      this.dirty = false;
    }
    depend() {
      if (this.dep) this.dep.depend();
    }
    update() {
      if (this.lazy) {
        this.dirty = true;
        if (this.dep) this.dep.notify();
      } else {
        const oldVal = this.value;
        const newVal = this.get();
        this.value = newVal;
        if (this.cb) this.cb.call(this.vm, newVal, oldVal);
      }
    }
  }

  function observe(data) {
    Object.keys(data).forEach(key => {
      let val = data[key];
      const dep = new Dep();
      Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get() { dep.depend(); return val; },
        set(newVal) {
          if (newVal === val) return;
          val = newVal;
          dep.notify();
        }
      });
    });
  }

  function evalExpr(vm, expr) {
    return new Function('with(this){ return (' + expr + '); }').call(vm);
  }

  class Vue {
    constructor(options) {
      this.$options = options || {};
      this.$data = options.data || {};
      observe(this.$data);
      Object.keys(this.$data).forEach(k => {
        Object.defineProperty(this, k, {
          enumerable: true,
          configurable: true,
          get: () => this.$data[k],
          set: (v) => { this.$data[k] = v; }
        });
      });
      const methods = options.methods || {};
      Object.keys(methods).forEach(m => { this[m] = methods[m].bind(this); });
      const computed = options.computed || {};
      this._computedWatchers = {};
      Object.keys(computed).forEach(k => {
        const def = computed[k];
        const getter = typeof def === 'function' ? def : def.get;
        const setter = typeof def === 'function' ? function () {} : (def.set || function () {});
        const watcher = new Watcher(this, getter, null, { lazy: true });
        this._computedWatchers[k] = watcher;
        Object.defineProperty(this, k, {
          enumerable: true,
          configurable: true,
          get() {
            if (watcher.dirty) watcher.evaluate();
            if (Dep.target) watcher.depend();
            return watcher.value;
          },
          set(newVal) { setter.call(this, newVal); }
        });
      });
      this.$el = typeof options.el === 'string' ? document.querySelector(options.el) : options.el;
      if (this.$el) this._compile(this.$el);
    }
    _compile(node) {
      Array.from(node.childNodes).forEach(child => {
        if (child.nodeType === 3 && /\{\{(.+?)\}\}/.test(child.textContent)) {
          const tpl = child.textContent;
          const render = () => tpl.replace(/\{\{(.+?)\}\}/g, (_, exp) => evalExpr(this, exp.trim()));
          const w = new Watcher(this, render, val => { child.textContent = val; });
          child.textContent = w.value;
        } else if (child.nodeType === 1) {
          this._compile(child);
        }
      });
    }
  }
  global.Vue = Vue;
})(window);
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue 2 计算属性 computed 实验</title></head>
<body>
  <div id="app">
    <p id="inline-rev">{{{{ message.split('').reverse().join('') }}}}</p>
    <p id="orig-msg">{{{{ message }}}}</p>
    <p id="comp-rev">{{{{ reversedMessage }}}}</p>
    <p id="site-out">{{{{ site }}}}</p>
    <p id="name-out">{{{{ name }}}}</p>
    <p id="url-out">{{{{ url }}}}</p>
  </div>
  <script>{MINI_VUE2_COMPUTED_JS}</script>
  <script>
    window.computedRuns = 0;
    window.methodRuns = 0;
    window.vm = new Vue({{
      el: '#app',
      data: {{
        message: 'Mbsky!',
        unrelated: 0,
        name: 'Google',
        url: 'https://www.google.com'
      }},
      computed: {{
        reversedMessage: function () {{
          window.computedRuns += 1;
          return this.message.split('').reverse().join('');
        }},
        site: {{
          get: function () {{
            return this.name + ' ' + this.url;
          }},
          set: function (newValue) {{
            var names = newValue.split(' ');
            this.name = names[0];
            this.url = names[names.length - 1];
          }}
        }}
      }},
      methods: {{
        reversedMessage2: function () {{
          window.methodRuns += 1;
          return this.message.split('').reverse().join('');
        }}
      }}
    }});
  </script>
</body>
</html>
"""


def launch_browser(pw):
    try:
        return pw.chromium.launch(headless=True)
    except Exception:
        return pw.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML_DOC)

        # Case 1: Inline template expression vs computed getter + reactive update
        res1 = page.evaluate("""() => {
            const initInline = document.getElementById('inline-rev').textContent;
            const initComp = document.getElementById('comp-rev').textContent;
            window.vm.message = 'Vue2';
            const updatedInline = document.getElementById('inline-rev').textContent;
            const updatedComp = document.getElementById('comp-rev').textContent;
            return {
                init_inline: initInline,
                init_computed: initComp,
                updated_inline: updatedInline,
                updated_computed: updatedComp
            };
        }""")
        exp1 = {
            "init_inline": "!yksbM",
            "init_computed": "!yksbM",
            "updated_inline": "2euV",
            "updated_computed": "2euV",
        }
        cases.append({
            "name": "inline_vs_computed_getter",
            "passed": res1 == exp1,
            "expected": exp1,
            "actual": res1,
        })

        # Case 2: Dependency caching of computed vs re-invocation of methods
        res2 = page.evaluate("""() => {
            window.computedRuns = 0;
            window.methodRuns = 0;
            window.vm.message = 'CacheA';
            // Reading computed 3 times with unchanged dependency
            const c1 = window.vm.reversedMessage;
            const c2 = window.vm.reversedMessage;
            const c3 = window.vm.reversedMessage;
            // Calling method 3 times
            const m1 = window.vm.reversedMessage2();
            const m2 = window.vm.reversedMessage2();
            const m3 = window.vm.reversedMessage2();
            const runsBeforeChange = { computed: window.computedRuns, method: window.methodRuns };
            // Changing unrelated property does not invalidate reversedMessage cache
            window.vm.unrelated = 99;
            const c4 = window.vm.reversedMessage;
            const runsAfterUnrelated = window.computedRuns;
            // Changing tracked dependency invalidates cache and recomputes once
            window.vm.message = 'CacheB';
            const c5 = window.vm.reversedMessage;
            const c6 = window.vm.reversedMessage;
            const m4 = window.vm.reversedMessage2();
            return {
                c_val_a: c1,
                m_val_a: m1,
                same_cached_value: (c1 === c2 && c2 === c3 && c3 === c4),
                runs_before_change: runsBeforeChange,
                runs_after_unrelated: runsAfterUnrelated,
                c_val_b: c5,
                c_b_consistent: c5 === c6 && c5 === m4,
                final_computed_runs: window.computedRuns,
                final_method_runs: window.methodRuns
            };
        }""")
        exp2 = {
            "c_val_a": "AehcaC",
            "m_val_a": "AehcaC",
            "same_cached_value": True,
            "runs_before_change": {"computed": 1, "method": 3},
            "runs_after_unrelated": 1,
            "c_val_b": "BehcaC",
            "c_b_consistent": True,
            "final_computed_runs": 2,
            "final_method_runs": 4,
        }
        cases.append({
            "name": "computed_cache_vs_methods_reexec",
            "passed": res2 == exp2,
            "expected": exp2,
            "actual": res2,
        })

        # Case 3: Computed getter & setter updating backing data and DOM
        res3 = page.evaluate("""() => {
            const beforeSite = document.getElementById('site-out').textContent;
            window.vm.site = '蓝色天空网 https://www.mbsky.com';
            return {
                before_site: beforeSite,
                after_name: window.vm.name,
                after_url: window.vm.url,
                dom_site: document.getElementById('site-out').textContent,
                dom_name: document.getElementById('name-out').textContent,
                dom_url: document.getElementById('url-out').textContent
            };
        }""")
        exp3 = {
            "before_site": "Google https://www.google.com",
            "after_name": "蓝色天空网",
            "after_url": "https://www.mbsky.com",
            "dom_site": "蓝色天空网 https://www.mbsky.com",
            "dom_name": "蓝色天空网",
            "dom_url": "https://www.mbsky.com",
        }
        cases.append({
            "name": "computed_getter_and_setter",
            "passed": res3 == exp3,
            "expected": exp3,
            "actual": res3,
        })

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/vue2-vue-computed-lab/explore-vue-computed.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-vue-computed.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Vue.js

课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip

下载课程关联工程包:Vue.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a780.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习