Vue3 组件
核对 Vue 3 组件树抽象、全局注册与复用状态隔离、局部注册、单文件组件 scoped 样式、静态/动态 Props 以及全量 Prop 类型与自定义校验规则。
学完这一章,你能够
- 核对 Vue 3 组件树抽象、全局注册与复用状态隔离、局部注册、单文件组件 scoped 样式、静态/动态 Props 以及全量 Prop 类型与自定义校验规则。
组件概念、五大优势与组件树抽象
组件(Component)是 Vue 3 构建大型应用的核心抽象:每个组件都是拥有独立模板、状态数据、方法与生命周期钩子的自包含实例,可扩展标准 HTML 元素并将页面拆解为清晰可维护的模块。组件体系具备五大工程优势:复用性(多处重复使用减少冗余)、封装性(独立作用域避免全局污染)、组合性(小组件逐层拼装复杂界面)、响应式(状态变更自动刷新视图)与模块化(无缝衔接现代前端构建工具链)。
几乎任意复杂页面都可以抽象为一棵自顶向下的组件树。使用 `Vue.createApp(RootComponent)` 配置根组件后,通过 `app.mount('#app')` 挂载到目标 DOM 容器,即确立整个组件树的渲染起点。
全局注册、组件复用与局部注册 / 单文件组件
通过 `app.component('my-component-name', { /* 配置选项 */ })` 可注册全局组件,注册后即可在该应用根模板及任意子组件模板中以 `<my-component-name></my-component-name>` 调用(多行模板字符串应使用反引号 `` ` `` 而非单引号)。因为每个组件实例都会重新执行 `data()` 返回独立状态对象,多次复用同一组件时彼此状态互不干扰。本站离线 Chromium 实测注册全局标题组件与 3 个 `<button-counter>` 实例,分别点击第 1 个按钮两次、第 2 个一次后,三个按钮独立显示 `点了 2 次!`、`点了 1 次!`、`点了 0 次!`。
全局注册会使未使用的组件仍保留在构建产物中,不利于按需打包(Tree-Shaking)。工程中更推荐用普通对象定义组件,再在父组件的 `components` 选项中以 `标签名: 组件对象` 形式局部注册,使其仅在当前组件作用域内生效;在工程化项目里则常用 `.vue` 单文件组件把 `<template>`、`<script>` 与 `<style scoped>`(组件私有样式)清晰分块。本站离线 Chromium 实测验证局部组件仅在已注册的 `#local-app-a` 渲染出 `<h1>局部组件!</h1>`,未注册的 `#local-app-b` 不解析该标签;带作用域属性的私有样式使组件内 `<p>` 呈 `rgb(0, 0, 255)`,外部 `<p>` 保持 `rgb(0, 0, 0)`。
Props 数据传递与动态绑定
`prop` 是子组件在 `props` 选项中显式声明的自定义属性,用于接收父组件向下传递的任意数量、任意类型的数据。既可以直接传入静态字符串属性,也可以通过 `v-bind`(简写 `:`)将 Prop 动态绑定到父组件数据,父级状态变更会自动向下传导至子组件。本站离线 Chromium 实测验证静态 Prop 渲染 `['Alpha', 'Beta', 'Gamma']`,动态 `:id`/`:title` 结合 `v-for` 初始渲染 `['1 - Alpha', '2 - Beta', '3 - Gamma']`,更新父级第 2 项标题为 `Beta-V2` 后子组件视图即时刷新为 `2 - Beta-V2`。
Prop 运行时验证规则
将 `props` 从字符串数组改为配置对象后,可为每个属性指定验证规则(Vue 3 中应通过应用实例 `app.component(...)` 注册而非 Vue 2 的全局 `Vue.component`):支持单类型检查(可选 Prop 传入 `null`/`undefined` 会跳过类型检查)、多类型数组 `[String, Number]`、必填 `required: true`、基础默认值 `default: 100`、对象/数组默认值工厂函数 `default() { return { ... } }`(确保多实例不共享同一引用)以及自定义校验函数 `validator(value)`。`type` 可取全部 8 种原生构造器(`String`、`Number`、`Boolean`、`Array`、`Object`、`Date`、`Function`、`Symbol`)或自定义类构造器(按 `instanceof` 检测),开发环境下校验失败将在控制台输出警告。本站离线 Chromium 实测覆盖全部 8 种原生构造器、自定义类 `Person`、工厂默认值双实例引用隔离(`factory_distinct_refs: true`),并在传入非法类型、缺失必填项与非法枚举值时精确捕获 3 条校验警告。
离线 Chromium 核对全局/局部组件隔离、scoped 样式、动态 Prop 与全量 Prop 校验
展开查看收起
"""Offline Playwright Chromium lab for Vue 3 Chapter 18 (components)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Vue3 Components Offline Lab</title>
<style>
[data-v-sfc1] p { color: rgb(0, 0, 255); }
</style>
</head>
<body>
<div id="global-app">
<div id="greet-host"></div>
<div id="counters-host"></div>
</div>
<div id="local-app-a"></div>
<div id="local-app-b"></div>
<div id="sfc-demo" data-v-sfc1>
<p id="sfc-p">Hello from MyComponent</p>
</div>
<p id="outside-p">Outside paragraph</p>
<div id="props-static"></div>
<div id="props-dynamic"></div>
<script>
function reactive(obj, onChange) {
return new Proxy(obj, {
set(t, k, v) { t[k] = v; onChange(); return true; }
});
}
// 1. Global component & isolated reuse instances
const globalComponents = {};
function registerGlobal(name, def) { globalComponents[name] = def; }
registerGlobal('greeting-box', {
mount(el) { el.innerHTML = '<h1>自定义组件!</h1>'; }
});
registerGlobal('button-counter', {
mount(el, idx) {
// Fresh data() object per component instance
const state = reactive({ count: 0 }, render);
const btn = document.createElement('button');
btn.id = 'counter-' + idx;
btn.addEventListener('click', () => { state.count++; });
function render() { btn.textContent = `点了 ${state.count} 次!`; }
render();
el.appendChild(btn);
}
});
globalComponents['greeting-box'].mount(document.getElementById('greet-host'));
const countersHost = document.getElementById('counters-host');
for (let i = 1; i <= 3; i++) {
globalComponents['button-counter'].mount(countersHost, i);
}
// 2. Local component scope isolation
const LocalCard = { template: '<h1>局部组件!</h1>' };
function mountWithLocal(selector, localMap) {
const host = document.querySelector(selector);
if (localMap && localMap['local-card']) {
host.innerHTML = localMap['local-card'].template;
} else {
host.innerHTML = '<local-card data-unresolved="true"></local-card>';
}
}
mountWithLocal('#local-app-a', { 'local-card': LocalCard });
mountWithLocal('#local-app-b', {});
// 3. Static & Dynamic Props
const staticTitles = ['Alpha', 'Beta', 'Gamma'];
const staticHost = document.getElementById('props-static');
staticTitles.forEach(t => {
const h4 = document.createElement('h4'); h4.textContent = t; staticHost.appendChild(h4);
});
const dynSites = [
{ id: 1, title: 'Alpha' },
{ id: 2, title: 'Beta' },
{ id: 3, title: 'Gamma' }
];
function renderDynProps() {
const host = document.getElementById('props-dynamic');
host.innerHTML = '';
dynSites.forEach(site => {
const h4 = document.createElement('h4');
h4.textContent = `${site.id} - ${site.title}`;
host.appendChild(h4);
});
}
renderDynProps();
window.__updateSiteTitle = (idx, title) => { dynSites[idx].title = title; renderDynProps(); };
// 4. Prop validation engine covering all 8 native constructors + custom class + required + default + validator
class Person { constructor(name) { this.name = name; } }
function checkType(val, typeCtor) {
if (typeCtor === String) return typeof val === 'string';
if (typeCtor === Number) return typeof val === 'number';
if (typeCtor === Boolean) return typeof val === 'boolean';
if (typeCtor === Array) return Array.isArray(val);
if (typeCtor === Object) return val !== null && typeof val === 'object' && !Array.isArray(val);
if (typeCtor === Date) return val instanceof Date;
if (typeCtor === Function) return typeof val === 'function';
if (typeCtor === Symbol) return typeof val === 'symbol';
return val instanceof typeCtor;
}
function validateProps(schema, rawProps) {
const warnings = [];
const resolved = {};
for (const [key, rule] of Object.entries(schema)) {
const def = typeof rule === 'function' || Array.isArray(rule) ? { type: rule } : rule;
let val = rawProps[key];
if (val === undefined) {
if (def.required) {
warnings.push(`missing required prop: ${key}`);
continue;
}
if ('default' in def) {
val = typeof def.default === 'function' && def.type !== Function ? def.default() : def.default;
}
}
resolved[key] = val;
if (val === null || val === undefined) continue;
if (def.type) {
const types = Array.isArray(def.type) ? def.type : [def.type];
if (!types.some(t => checkType(val, t))) {
warnings.push(`type mismatch on ${key}`);
}
}
if (typeof def.validator === 'function' && !def.validator(val)) {
warnings.push(`validator failed on ${key}`);
}
}
return { resolved, warnings };
}
window.__runPropValidation = () => {
const schema = {
propA: Number,
propB: [String, Number],
propC: { type: String, required: true },
propD: { type: Number, default: 100 },
propE: { type: Object, default() { return { message: 'hello' }; } },
propF: { validator: (v) => ['success', 'warning', 'danger'].includes(v) },
propBool: Boolean,
propArr: Array,
propDate: Date,
propFn: Function,
propSym: Symbol,
propPerson: Person
};
const valid1 = validateProps(schema, {
propA: null,
propB: 'ok',
propC: 'required-text',
propF: 'warning',
propBool: true,
propArr: [1, 2],
propDate: new Date(2026, 0, 1),
propFn: () => 1,
propSym: Symbol('id'),
propPerson: new Person('Ada')
});
const valid2 = validateProps(schema, { propC: 'second' });
const invalid = validateProps(schema, { propA: 'not-a-num', propF: 'invalid-status' });
return {
valid_warnings: valid1.warnings,
default_num: valid1.resolved.propD,
default_obj_msg: valid1.resolved.propE.message,
factory_distinct_refs: valid1.resolved.propE !== valid2.resolved.propE,
invalid_warnings: invalid.warnings
};
};
</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: Global component & 3 reused instances with isolated data() state
page.click("#counter-1")
page.click("#counter-1")
page.click("#counter-2")
c1 = page.evaluate("""() => ({
greeting: document.querySelector('#greet-host h1').textContent,
counters: [
document.getElementById('counter-1').textContent,
document.getElementById('counter-2').textContent,
document.getElementById('counter-3').textContent
]
})""")
exp1 = {
"greeting": "自定义组件!",
"counters": ["点了 2 次!", "点了 1 次!", "点了 0 次!"],
}
cases.append({"name": "global_component_and_reuse_isolation", "passed": c1 == exp1, "expected": exp1, "actual": c1})
# Case 2: Local component scope & SFC scoped style isolation
c2 = page.evaluate("""() => ({
app_a_h1: document.querySelector('#local-app-a h1')?.textContent || null,
app_b_has_h1: document.querySelector('#local-app-b h1') !== null,
app_b_unresolved: document.querySelector('#local-app-b local-card')?.dataset.unresolved === 'true',
sfc_p_color: getComputedStyle(document.getElementById('sfc-p')).color,
outside_p_color: getComputedStyle(document.getElementById('outside-p')).color
})""")
exp2 = {
"app_a_h1": "局部组件!",
"app_b_has_h1": False,
"app_b_unresolved": True,
"sfc_p_color": "rgb(0, 0, 255)",
"outside_p_color": "rgb(0, 0, 0)",
}
cases.append({"name": "local_component_scope", "passed": c2 == exp2, "expected": exp2, "actual": c2})
# Case 3: Static & dynamic props propagation
c3 = page.evaluate("""() => {
const statics = Array.from(document.querySelectorAll('#props-static h4')).map(el => el.textContent);
const dynBefore = Array.from(document.querySelectorAll('#props-dynamic h4')).map(el => el.textContent);
window.__updateSiteTitle(1, 'Beta-V2');
const dynAfter = Array.from(document.querySelectorAll('#props-dynamic h4')).map(el => el.textContent);
return { statics, dyn_before: dynBefore, dyn_after: dynAfter };
}""")
exp3 = {
"statics": ["Alpha", "Beta", "Gamma"],
"dyn_before": ["1 - Alpha", "2 - Beta", "3 - Gamma"],
"dyn_after": ["1 - Alpha", "2 - Beta-V2", "3 - Gamma"],
}
cases.append({"name": "static_and_dynamic_props", "passed": c3 == exp3, "expected": exp3, "actual": c3})
# Case 4: Prop validation rules (8 native ctors, custom class, defaults, validator)
c4 = page.evaluate("() => window.__runPropValidation()")
exp4 = {
"valid_warnings": [],
"default_num": 100,
"default_obj_msg": "hello",
"factory_distinct_refs": True,
"invalid_warnings": [
"type mismatch on propA",
"missing required prop: propC",
"validator failed on propF",
],
}
cases.append({"name": "prop_validation_rules", "passed": c4 == exp4, "expected": exp4, "actual": c4})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
若直接写对象字面量,所有未传入该 Prop 的组件实例将共享同一块内存引用,修改其中一个实例的对象属性会意外污染其他实例;写成工厂函数可在每次实例化时返回全新对象副本。