Vue3 起步
核对 Vue 3 的 createApp 应用创建与 mount 挂载机制、根组件内联模板与 setup/ref 组合式写法、data 响应式代理与 methods 方法绑定。
学完这一章,你能够
- 核对 Vue 3 的 createApp 应用创建与 mount 挂载机制、根组件内联模板与 setup/ref 组合式写法、data 响应式代理与 methods 方法绑定。
创建应用实例与挂载到 DOM 容器
Vue.js 是用于构建用户界面的渐进式 JavaScript 框架。入门阶段无需先配置脚手架工程,直接在 HTML 页面中引入 `vue.global.js` 即可快速试验核心能力。Vue 3 通过 `Vue.createApp({ /* 根组件选项 */ })` 创建应用实例,传入的配置对象定义根组件行为;应用实例只有在调用 `.mount()` 并传入真实 DOM 节点或 CSS 选择器字符串(例如 `#app` 或 `#hello-vue`)后才会执行首次渲染。
最基础的 Hello Vue 示例由页面容器 `<div id="hello-vue" class="demo">{{ message }}</div>` 与脚本两部分组成:加载 Vue 3 运行时后,调用 `Vue.createApp(HelloVueApp).mount('#hello-vue')` 将根组件挂载到该容器。双大括号 `{{ }}` 负责输出组件属性或函数返回值,其中的 `{{ message }}` 会绑定至 `data()` 返回对象的 `message` 字段。本站离线 Chromium 实测确认挂载容器保留 `id="hello-vue"` 与 `class="demo"`,初始渲染为 `Hello Vue!!`,修改 `vm.message = 'Vue 3 Ready'` 后页面文本同步更新为 `Vue 3 Ready`。
根组件内联模板与 setup / ref 写法
根组件的模板既可以写在组件选项的 `template` 字段内,也可以直接写在挂载容器的 HTML 结构里。当根组件未显式提供 `template` 选项时,Vue 3 会自动读取挂载容器的 `innerHTML` 作为模板进行解析与绑定。
在组合式写法中,组件状态与行为常组织在 `setup()` 函数内:调用 `ref(0)` 创建响应式引用 `count`,定义 `increment()` 并在其中通过 `count.value++` 递增数值,最后将 `{ count, increment }` 返回给模板(模板中自动解包 `ref`,无需再写 `.value`)。本站离线 Chromium 实测对容器内 `<button @click="increment">{{ count }}</button>` 连续点击两次,按钮文本由 `0` 依次变为 `1`、`2`,同时实例 `count` 值精确同步为 `2`。
data 响应式选项与 methods 方法绑定
选项式写法中的 `data` 必须是一个函数。Vue 3 在创建组件实例时调用该函数,将返回对象纳入响应式系统并以 `vm.$data` 挂在实例上,同时把其顶层属性代理到组件实例 `vm` 自身。由于这些响应式属性在实例初始化阶段注册,应把会参与渲染的状态提前声明在 `data()` 返回对象中。本站离线 Chromium 实测验证初始 `vm.$data.count` 与 `vm.count` 均为 `4`,赋值 `vm.count = 5` 时 `vm.$data.count` 与 DOM 同步更新为 `5`,再赋值 `vm.$data.count = 6` 时 `vm.count` 与 DOM 同步更新为 `6`。
组件交互逻辑可声明在 `methods` 选项对象中,Vue 3 会自动将方法内的 `this` 绑定到当前组件实例(因此不宜在 `methods` 中使用箭头函数定义顶层方法)。本站离线 Chromium 实测在 `count: 4` 的实例上调用 `vm.increment()` 后计数与 DOM 更新为 `5`,再点击绑定按钮后更新为 `6`。
离线 Chromium 核对 createApp 挂载、setup/ref、data 代理与 methods
"""Offline Playwright Chromium lab for Vue 3 Chapter 11 (intro)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Intro Offline Lab</title></head>
<body>
<div id="hello-vue" class="demo">{{ message }}</div>
<div id="setup-app">
<button id="btn-inc" @click="increment">{{ count }}</button>
</div>
<div id="data-app">
<span id="data-val">{{ count }}</span>
</div>
<div id="methods-app">
<span id="method-val">{{ count }}</span>
<button id="btn-method" @click="increment">+1</button>
</div>
<script>
const MiniVue = (() => {
function ref(initial) {
let _val = initial;
const subs = new Set();
return {
__isRef: true,
get value() { return _val; },
set value(v) {
if (v !== _val) {
_val = v;
subs.forEach(fn => fn());
}
},
_sub(fn) { subs.add(fn); }
};
}
function reactive(obj, onUpdate) {
return new Proxy(obj, {
get(target, key, receiver) {
return Reflect.get(target, key, receiver);
},
set(target, key, val, receiver) {
const ok = Reflect.set(target, key, val, receiver);
onUpdate();
return ok;
}
});
}
function createApp(options) {
return {
mount(selector) {
const el = typeof selector === 'string' ? document.querySelector(selector) : selector;
const template = options.template || el.innerHTML;
const rawData = typeof options.data === 'function' ? options.data() : {};
const listeners = [];
const render = () => {
// Evaluate mustache expressions in text nodes cleanly
el.innerHTML = template.replace(/\{\{\s*([^}]+)\s*\}\}/g, (_, expr) => {
const key = expr.trim();
if (setupResult && key in setupResult) {
const v = setupResult[key];
return v && v.__isRef ? String(v.value) : String(v);
}
return String(vm[key]);
});
// Bind @click handlers
el.querySelectorAll('*').forEach(node => {
if (!node.hasAttribute('@click')) return;
const handlerName = node.getAttribute('@click').trim();
node.removeAttribute('@click');
node.addEventListener('click', () => {
if (setupResult && typeof setupResult[handlerName] === 'function') {
setupResult[handlerName]();
} else if (typeof vm[handlerName] === 'function') {
vm[handlerName]();
}
});
});
};
const $data = reactive(rawData, render);
const methods = options.methods || {};
let setupResult = null;
const vmTarget = { $data };
const vm = new Proxy(vmTarget, {
get(target, key) {
if (key === '$data') return $data;
if (key in $data) return $data[key];
if (key in methods) return methods[key].bind(vm);
if (setupResult && key in setupResult) {
const v = setupResult[key];
return v && v.__isRef ? v.value : v;
}
return target[key];
},
set(target, key, val) {
if (key in $data) {
$data[key] = val;
return true;
}
if (setupResult && key in setupResult && setupResult[key] && setupResult[key].__isRef) {
setupResult[key].value = val;
return true;
}
target[key] = val;
return true;
}
});
if (typeof options.setup === 'function') {
setupResult = options.setup();
Object.values(setupResult).forEach(v => {
if (v && v.__isRef) v._sub(render);
});
}
render();
return vm;
}
};
}
return { createApp, ref };
})();
window.__vms = {};
// App 1: HelloVueApp
const HelloVueApp = {
data() {
return { message: 'Hello Vue!!' };
}
};
window.__vms.hello = MiniVue.createApp(HelloVueApp).mount('#hello-vue');
// App 2: setup + ref + root container template
const { createApp, ref } = MiniVue;
window.__vms.setup = createApp({
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return { count, increment };
}
}).mount('#setup-app');
// App 3: data() & $data bidirectional proxy
window.__vms.dataVm = MiniVue.createApp({
data() {
return { count: 4 };
}
}).mount('#data-app');
// App 4: methods option with `this`
window.__vms.methodsVm = MiniVue.createApp({
data() {
return { count: 4 };
},
methods: {
increment() {
this.count++;
}
}
}).mount('#methods-app');
</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(viewport={"width": 900, "height": 600})
page.set_content(HTML_DOC)
# Case 1: createApp + mount('#hello-vue') + mustache interpolation
c1 = page.evaluate("""() => {
const el = document.getElementById('hello-vue');
const initial = el.textContent.trim();
window.__vms.hello.message = 'Vue 3 Ready';
const updated = el.textContent.trim();
return { id: el.id, className: el.className, initial, updated };
}""")
exp1 = {"id": "hello-vue", "className": "demo", "initial": "Hello Vue!!", "updated": "Vue 3 Ready"}
cases.append({"name": "create_app_mount_mustache", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: setup() + ref() + container innerHTML root template
initial_btn = page.locator("#btn-inc").inner_text().strip()
page.click("#btn-inc")
after_1 = page.locator("#btn-inc").inner_text().strip()
page.click("#btn-inc")
after_2 = page.locator("#btn-inc").inner_text().strip()
vm_count = page.evaluate("() => window.__vms.setup.count")
c2 = {"initial": initial_btn, "after_click_1": after_1, "after_click_2": after_2, "vm_count": vm_count}
exp2 = {"initial": "0", "after_click_1": "1", "after_click_2": "2", "vm_count": 2}
cases.append({"name": "setup_ref_root_template", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: data() proxy synchronization between vm.count and vm.$data.count
c3 = page.evaluate("""() => {
const vm = window.__vms.dataVm;
const out = {
init_data: vm.$data.count,
init_vm: vm.count,
init_dom: document.getElementById('data-val').textContent.trim()
};
vm.count = 5;
out.after_vm_set_data = vm.$data.count;
out.after_vm_set_dom = document.getElementById('data-val').textContent.trim();
vm.$data.count = 6;
out.after_data_set_vm = vm.count;
out.after_data_set_dom = document.getElementById('data-val').textContent.trim();
return out;
}""")
exp3 = {
"init_data": 4,
"init_vm": 4,
"init_dom": "4",
"after_vm_set_data": 5,
"after_vm_set_dom": "5",
"after_data_set_vm": 6,
"after_data_set_dom": "6",
}
cases.append({"name": "data_proxy_sync", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: methods option binding `this` to component instance
init_m = page.evaluate("() => ({ count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() })")
after_call = page.evaluate("() => { window.__vms.methodsVm.increment(); return { count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() }; }")
page.click("#btn-method")
after_click = page.evaluate("() => ({ count: window.__vms.methodsVm.count, dom: document.getElementById('method-val').textContent.trim() })")
c4 = {"init": init_m, "after_vm_increment": after_call, "after_btn_click": after_click}
exp4 = {
"init": {"count": 4, "dom": "4"},
"after_vm_increment": {"count": 5, "dom": "5"},
"after_btn_click": {"count": 6, "dom": "6"},
}
cases.append({"name": "methods_this_increment", "passed": c4 == exp4, "expected": exp4, "actual": c4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 #hello-vue 初始渲染与响应式更新,setup/ref 按钮点击 0→1→2,vm.count 与 vm.$data.count 4→5→6 双向同步,以及 methods 的 this.count++ 4→5→6。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:29e159fdeb011ed94b2ed204b8bb08250add9e5cbc0a34cb36585a774f7cc719
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:15bb17a189716f40fc5fc0e1ecd2f5852912651b19161bef85ce6b44ca8313c0
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Vue 3 的 data 选项必须写成返回对象的函数,以及在 setup() 中修改 ref 数值与在模板中读取它有何区别?
展开参考解答
将 data 写成函数可确保每次创建组件实例都获得独立状态对象而互不串改;在 setup() 脚本内读写 ref 必须访问 .value 属性,而在模板中使用返回给模板的顶层 ref 时会自动解包,直接写变量名即可。