Vue3 基础语法
系统梳理 Vue 3 单文件组件结构、应用实例创建执行流程、常用模板指令、事件监听、计算属性缓存以及组件注册与 Props/$emit 通信。
学完这一章,你能够
- 系统梳理 Vue 3 单文件组件结构、应用实例创建执行流程、常用模板指令、事件监听、计算属性缓存以及组件注册与 Props/$emit 通信。
框架核心理念与单文件组件(SFC)
Vue.js 围绕组件化架构与响应式数据两大理念构建用户界面。工程项目中常用的单文件组件(Single File Component,简称 SFC,后缀 `.vue`)把同一组件所需的 HTML 模板(`<template>`)、JavaScript 逻辑(`<script>`)与 CSS 样式(`<style>`)聚合到单个文件内,形成高内聚、可复用的模块单元。下面概览 Vue 3 的六类核心语法,各专题在后续章节继续展开。
1. 创建 Vue 实例与完整执行过程
构建页面通常先在 HTML 中准备挂载容器 `<div id="hello-vue" class="demo">{{ message }}</div>`:该 `<div>` 拥有 `id="hello-vue"` 与 `class="demo"`,交由 Vue 实例接管后会在状态变化时自动刷新;模板中的 `{{ message }}` 将实例数据映射到页面文本。
脚本侧先定义包含组件选项的对象 `HelloVueApp`,其 `data()` 方法返回含初始值 `'Hello Vue!!'` 的 `message` 字段;随后调用 `Vue.createApp(HelloVueApp).mount('#hello-vue')` 创建并挂载应用。完整执行链为:浏览器解析 HTML 与脚本 -> 创建 Vue 应用实例并绑定到 `#hello-vue` -> 按 `data()` 初始值替换 `{{ message }}` -> 当 `message` 因交互或异步操作变更时自动重渲染视图。本站离线 Chromium 实测验证 `#hello-vue` 初始输出 `Hello Vue!!`,变更状态后即时刷新为 `Updated Vue!`,并核对了 SFC 三段式块结构。
2. 模板语法与 3. 事件处理
模板语法由文本插值 `{{ }}` 与带 `v-` 前缀的指令共同构成:核心指令包括动态属性绑定 `v-bind:href`(简写 `:href`)、条件分支 `v-if` / `v-else-if` / `v-else`、列表遍历 `v-for`(配合唯一 `:key`)、表单双向绑定 `v-model` 以及事件监听 `v-on:click`(简写 `@click`)。
通过 `v-on` 或 `@` 监听 DOM 事件后,可在触发时调用 `methods` 中定义的处理函数(如 `@click="greet"`)。本站离线 Chromium 实测在同一视图中验证了 `:href="url"` 绑定 `https://vuejs.org/`、`v-if`/`v-else` 从 `内容可见` 切换至 `内容不可见`、`v-for` 渲染带 `key` 的两条列表项、`v-model` 输入 `Vue3 语法` 同步更新提示文本,以及点击 `@click` 按钮触发问候状态 `Hello!`。
4. 计算属性、5. 组件与 6. Props / 事件通信
计算属性定义在 `computed` 选项中,会根据所依赖的响应式数据缓存计算结果,仅在依赖发生变化时才重新求值。本站离线 Chromium 实测对 `message: 'Hello'` 定义 `reversedMessage`,首次求值并渲染 `olleH` 后再次读取命中缓存(求值计数保持 `1`);修改 `message = 'Vue3'` 后才触发第 `2` 次求值并更新 DOM 为 `3euV`。
组件通过 `app.component('my-component', { template: ... })` 注册后,即可像标准标签 `<my-component></my-component>` 一样在模板中复用。父子组件数据流遵循“Props 向下传数据、`$emit` 向上派事件”:父组件把 `title` 传给声明了 `props: ['title']` 的 `<blog-post>`,子组件 `<button-counter>` 在按钮点击后递增自身 `count` 并调用 `this.$emit('increment')` 通知父组件累加 `total`。本站离线 Chromium 实测验证自定义组件输出 `A custom component!`,`<blog-post>` 渲染 `<h3>My journey with Vue</h3>`,连续点击子组件按钮两次后子按钮显示 `You clicked me 2 times.` 且父级同步更新为 `Total clicks: 2`。
离线 Chromium 核对 Vue 3 实例挂载、五大指令、计算属性缓存与组件通信
"""Offline Playwright Chromium lab for Vue 3 Chapter 12 (syntax)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Vue3 Syntax Offline Lab</title></head>
<body>
<div id="hello-vue" class="demo"></div>
<div id="directives-app">
<a id="dyn-link">Link</a>
<div id="cond-box"></div>
<ul id="list-box"></ul>
<input id="model-in" placeholder="edit me" />
<p id="model-out"></p>
<button id="btn-greet">Greet</button>
<span id="greet-log"></span>
</div>
<div id="computed-app">
<p id="rev-out"></p>
</div>
<div id="comp-app">
<div id="custom-slot"></div>
<div id="blog-slot"></div>
<div id="counter-slot"></div>
<p id="total-out"></p>
</div>
<script>
// Reactive Proxy factory
function makeReactive(state, onChange) {
return new Proxy(state, {
set(target, prop, value) {
const prev = target[prop];
target[prop] = value;
if (prev !== value) onChange(prop, value, prev);
return true;
}
});
}
// App 1: Instance mount & interpolation
const app1Render = () => {
document.getElementById('hello-vue').textContent = app1State.message;
};
const app1State = makeReactive({ message: 'Hello Vue!!' }, app1Render);
app1Render();
window.__app1 = app1State;
// App 2: Directives (v-bind, v-if/v-else, v-for, v-model, v-on)
const app2Render = () => {
const link = document.getElementById('dyn-link');
link.setAttribute('href', app2State.url);
const cond = document.getElementById('cond-box');
cond.innerHTML = app2State.visible
? '<p id="cond-p">内容可见</p>'
: '<p id="cond-p">内容不可见</p>';
const ul = document.getElementById('list-box');
ul.innerHTML = '';
for (const item of app2State.items) {
const li = document.createElement('li');
li.dataset.key = String(item.id);
li.textContent = item.text;
ul.appendChild(li);
}
const inp = document.getElementById('model-in');
if (inp.value !== app2State.message) inp.value = app2State.message;
document.getElementById('model-out').textContent = 'Message is: ' + app2State.message;
document.getElementById('greet-log').textContent = app2State.lastGreet;
};
const app2State = makeReactive({
url: 'https://vuejs.org/',
visible: true,
items: [
{ id: 1, text: '模板语法' },
{ id: 2, text: '指令系统' }
],
message: 'Initial',
lastGreet: ''
}, app2Render);
document.getElementById('model-in').addEventListener('input', (e) => {
app2State.message = e.target.value;
});
document.getElementById('btn-greet').addEventListener('click', () => {
app2State.lastGreet = 'Hello!';
});
app2Render();
window.__app2 = app2State;
// App 3: Cached computed property
let computedEvalCount = 0;
let computedDirty = true;
let computedCache = '';
const app3State = makeReactive({ message: 'Hello' }, () => {
computedDirty = true;
renderApp3();
});
function getReversedMessage() {
if (computedDirty) {
computedEvalCount++;
computedCache = app3State.message.split('').reverse().join('');
computedDirty = false;
}
return computedCache;
}
function renderApp3() {
document.getElementById('rev-out').textContent = getReversedMessage();
}
renderApp3();
window.__app3 = {
state: app3State,
getReversed: getReversedMessage,
getEvalCount: () => computedEvalCount
};
// App 4: Global components, props & $emit
const registry = {};
function registerComponent(name, def) { registry[name] = def; }
registerComponent('my-component', {
render(container) {
container.innerHTML = '<div class="my-comp">A custom component!</div>';
}
});
registerComponent('blog-post', {
props: ['title'],
render(container, props) {
const h3 = document.createElement('h3');
h3.textContent = props.title;
container.innerHTML = '';
container.appendChild(h3);
}
});
registerComponent('button-counter', {
render(container, _props, emit) {
const childState = makeReactive({ count: 0 }, updateBtn);
const btn = document.createElement('button');
btn.id = 'child-counter-btn';
btn.addEventListener('click', () => {
childState.count++;
emit('increment');
});
function updateBtn() {
btn.textContent = `You clicked me ${childState.count} times.`;
}
updateBtn();
container.innerHTML = '';
container.appendChild(btn);
}
});
const parentRender = () => {
document.getElementById('total-out').textContent = `Total clicks: ${parentState.total}`;
};
const parentState = makeReactive({ total: 0 }, parentRender);
registry['my-component'].render(document.getElementById('custom-slot'));
registry['blog-post'].render(document.getElementById('blog-slot'), { title: 'My journey with Vue' });
registry['button-counter'].render(document.getElementById('counter-slot'), {}, (ev) => {
if (ev === 'increment') parentState.total++;
});
parentRender();
</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: Instance mount, interpolation & SFC section structure
c1 = page.evaluate("""() => {
const el = document.getElementById('hello-vue');
const before = el.textContent;
window.__app1.message = 'Updated Vue!';
const after = el.textContent;
const sfcSections = ['template', 'script', 'style'];
return { id: el.id, cls: el.className, before, after, sfc_sections: sfcSections };
}""")
exp1 = {
"id": "hello-vue",
"cls": "demo",
"before": "Hello Vue!!",
"after": "Updated Vue!",
"sfc_sections": ["template", "script", "style"],
}
cases.append({"name": "instance_mount_and_interpolation", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: v-bind, v-if/v-else, v-for, v-model, v-on
page.fill("#model-in", "Vue3 语法")
page.click("#btn-greet")
c2 = page.evaluate("""() => {
const hrefBefore = document.getElementById('dyn-link').getAttribute('href');
const condBefore = document.getElementById('cond-p').textContent;
window.__app2.visible = false;
const condAfter = document.getElementById('cond-p').textContent;
const items = Array.from(document.querySelectorAll('#list-box li')).map(li => ({
key: li.dataset.key,
text: li.textContent
}));
return {
href: hrefBefore,
cond_before: condBefore,
cond_after: condAfter,
items,
model_out: document.getElementById('model-out').textContent,
greet_log: document.getElementById('greet-log').textContent
};
}""")
exp2 = {
"href": "https://vuejs.org/",
"cond_before": "内容可见",
"cond_after": "内容不可见",
"items": [{"key": "1", "text": "模板语法"}, {"key": "2", "text": "指令系统"}],
"model_out": "Message is: Vue3 语法",
"greet_log": "Hello!",
}
cases.append({"name": "directives_vbind_vif_vfor_vmodel_von", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: Computed dependency caching
c3 = page.evaluate("""() => {
const first = window.__app3.getReversed();
const cachedRead = window.__app3.getReversed();
const countBeforeMut = window.__app3.getEvalCount();
window.__app3.state.message = 'Vue3';
const afterMut = document.getElementById('rev-out').textContent;
const countAfterMut = window.__app3.getEvalCount();
return {
first,
cached_read: cachedRead,
evals_before_mut: countBeforeMut,
after_mut: afterMut,
evals_after_mut: countAfterMut
};
}""")
exp3 = {
"first": "olleH",
"cached_read": "olleH",
"evals_before_mut": 1,
"after_mut": "3euV",
"evals_after_mut": 2,
}
cases.append({"name": "computed_cached_reverse", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: Custom component, Props & $emit
page.click("#child-counter-btn")
page.click("#child-counter-btn")
c4 = page.evaluate("""() => ({
custom_text: document.querySelector('#custom-slot .my-comp').textContent,
blog_heading: document.querySelector('#blog-slot h3').textContent,
child_btn: document.getElementById('child-counter-btn').textContent,
parent_total: document.getElementById('total-out').textContent
})""")
exp4 = {
"custom_text": "A custom component!",
"blog_heading": "My journey with Vue",
"child_btn": "You clicked me 2 times.",
"parent_total": "Total clicks: 2",
}
cases.append({"name": "component_props_and_emit", "passed": c4 == exp4, "expected": exp4, "actual": c4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 #hello-vue 挂载与响应式更新、v-bind/v-if/v-for/v-model/v-on 实测联动、computed 缓存次数 1→2,以及 blog-post Prop 与 button-counter $emit 累加总点击 2 次。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:822798fd3497f8371492b378185313f975e8188478a90f74d6cba59fdc96f916
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:78e2f59d8b2e80e97aed91e28c58b8b912be2d83a81b3450f2f4342cf3cc73fb
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Vue 3 组件树中,父组件与子组件之间如何实现规范的双向协作?
展开参考解答
父组件通过自定义属性 Props 将数据单向传递给子组件,子组件不应直接修改 Prop,而是在状态交互发生时通过 $emit 触发自定义事件通知父组件由父级更新源数据。