"""Offline Playwright Chromium lab for Vue 2 Chapter 04 (vue-start)."""
import json
from playwright.sync_api import sync_playwright
MINI_VUE2_JS = r"""
(function (global) {
class Dep {
constructor() { this.subs = new Set(); }
depend() { if (Dep.target) this.subs.add(Dep.target); }
notify() { this.subs.forEach(w => w.update()); }
}
Dep.target = null;
class Watcher {
constructor(vm, getter, cb) {
this.vm = vm;
this.getter = getter;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const v = this.getter.call(this.vm);
Dep.target = null;
return v;
}
update() {
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);
});
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 起步与实例代理实验</title></head>
<body>
<div id="outside">{{{{ site }}}}</div>
<div id="vue_det">
<h1 id="out-site">site : {{{{ site }}}}</h1>
<h1 id="out-url">url : {{{{ url }}}}</h1>
<h1 id="out-details">{{{{ details() }}}}</h1>
</div>
<div id="vue_shared">
<p id="s-site">{{{{ site }}}}</p>
<p id="s-alexa">{{{{ alexa }}}}</p>
</div>
<script>{MINI_VUE2_JS}</script>
<script>
window.vm1 = new Vue({{
el: '#vue_det',
data: {{
site: '蓝色天空网',
url: 'www.mbsky.com',
alexa: '10000'
}},
methods: {{
details: function () {{
return this.site + ' - 渐进式前端实践';
}}
}}
}});
window.sharedData = {{
site: '蓝色天空网',
url: 'www.mbsky.com',
alexa: 10000
}};
window.vm2 = new Vue({{
el: '#vue_shared',
data: window.sharedData
}});
</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: el scope, data properties, methods return value, outside isolation
res1 = page.evaluate("""() => ({
site_h1: document.getElementById('out-site').textContent,
url_h1: document.getElementById('out-url').textContent,
details_h1: document.getElementById('out-details').textContent,
outside_literal: document.getElementById('outside').textContent
})""")
exp1 = {
"site_h1": "site : 蓝色天空网",
"url_h1": "url : www.mbsky.com",
"details_h1": "蓝色天空网 - 渐进式前端实践",
"outside_literal": "{{ site }}",
}
cases.append({
"name": "vue_instance_el_data_methods",
"passed": res1 == exp1,
"expected": exp1,
"actual": res1,
})
# Case 2: Shared data object reference & bidirectional proxy mutation
res2 = page.evaluate("""() => {
const sameRefBefore = (window.vm2.site === window.sharedData.site);
window.vm2.site = 'MBSKY';
const dataSiteAfterVmWrite = window.sharedData.site;
const domSiteAfterVmWrite = document.getElementById('s-site').textContent;
window.sharedData.alexa = 1234;
const vmAlexaAfterDataWrite = window.vm2.alexa;
const domAlexaAfterDataWrite = document.getElementById('s-alexa').textContent;
return {
same_ref_before: sameRefBefore,
data_site_after_vm_write: dataSiteAfterVmWrite,
dom_site_after_vm_write: domSiteAfterVmWrite,
vm_alexa_after_data_write: vmAlexaAfterDataWrite,
dom_alexa_after_data_write: domAlexaAfterDataWrite
};
}""")
exp2 = {
"same_ref_before": True,
"data_site_after_vm_write": "MBSKY",
"dom_site_after_vm_write": "MBSKY",
"vm_alexa_after_data_write": 1234,
"dom_alexa_after_data_write": "1234",
}
cases.append({
"name": "shared_data_reactivity_proxy",
"passed": res2 == exp2,
"expected": exp2,
"actual": res2,
})
# Case 3: $-prefixed built-in instance properties ($data, $el)
res3 = page.evaluate("""() => ({
dollar_data_exact: window.vm2.$data === window.sharedData,
dollar_el_exact: window.vm2.$el === document.getElementById('vue_shared'),
el_tag: window.vm2.$el.tagName
})""")
exp3 = {
"dollar_data_exact": True,
"dollar_el_exact": True,
"el_tag": "DIV",
}
cases.append({
"name": "instance_dollar_properties",
"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-start-lab/explore-vue-start.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vue-start.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a791.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a776.zip