Vue.js 组件
核对组件树抽象、全局与局部注册作用域、静态与动态 Prop 单向数据流、v-for 组件列表及 Props 完整校验规则。
学完这一章,你能够
- 核对组件树抽象、全局与局部注册作用域、静态与动态 Prop 单向数据流、v-for 组件列表及 Props 完整校验规则。
组件树抽象与全局/局部注册
组件(Component)用于扩展自定义 HTML 标签并封装可复用视图与逻辑,复杂界面可整体抽象为嵌套的组件树。全局组件通过 `Vue.component(tagName, options)` 注册,其中 `tagName` 为标签名、`options` 为配置对象,注册后在模板中以 `<tagName></tagName>` 调用。
全局组件可在所有根实例及子模板中直接使用,而通过实例选项 `components: { ... }` 注册的局部组件仅在声明它的父作用域内可见。本站离线 Chromium 实测两个独立根容器 `#app1`、`#app2`:全局组件 `global-card` 在两处均渲染出 `<h1>全局自定义组件!</h1>`,而仅在 `#app1` 注册的局部组件 `local-badge` 在 `#app1` 渲染成功、在 `#app2` 保持未解析(`app2BadgeCount = 0`,`app2Unresolved = ['local-badge']`)。
Prop 数据传递、动态绑定与列表复用
Prop 是子组件通过 `props` 选项显式声明的自定义特性,用于接收父组件下发的数据:既可传递静态字面量(如 `message="hello!"`),也可配合 `v-bind:message="parentMsg"` 动态绑定父组件状态,使父数据变化实时传导至子组件。需要注意 Prop 为单向数据流(父到子),子组件不应直接改写收到的 Prop。本站离线 Chromium 实测静态 Prop 渲染为 `hello!`,动态输入框改写为“父传子动态值”后子组件同步更新,而尝试在子侧修改冻结 Prop 无法反向污染父状态(`childMutatedParent = false`)。
结合 `v-for` 与 `v-bind` 可将数组中的每一项通过 Prop 下发给重复渲染的子组件(如 `<todo-item v-for="item in sites" v-bind:todo="item">`)。本站离线 Chromium 实测将 3 项数据依次渲染到 `<ol>` 中,输出列表项为 `['HTML', 'CSS', 'JavaScript']`。
Prop 类型检查与校验规则
除字符串数组外,`props` 还可配置为校验对象,支持基础类型检查(`null` 与 `undefined` 会通过非必填项的类型检查)、多类型数组(如 `[String, Number]`)、`required: true` 必填约束、`default` 默认值(对象或数组默认值必须由工厂函数返回,确保每个实例获得独立副本)以及自定义 `validator` 函数;开发环境校验失败会在控制台输出警告。`type` 可选 8 种原生构造器:`String`、`Number`、`Boolean`、`Array`、`Object`、`Date`、`Function`、`Symbol`,也支持自定义构造器并通过 `instanceof` 检测。本站离线实测全部规则:8 种原生类型与 `Author` 自定义类均准确判定,必填项缺失返回 `false`,对象工厂两次生成不同引用(`e1 !== e2`),自定义枚举校验接受 `'warning'` 并拒绝 `'unknown'`。
离线 Chromium 验证组件作用域、单向 Props 与校验器
展开查看收起
"""Offline Chromium runtime verification for Vue 2 Chapter 13: vue-component."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
# Case 1: global vs local component registration scope
page.set_content("""
<!doctype html>
<html><body>
<div id="app1"><global-card></global-card><local-badge></local-badge></div>
<div id="app2"><global-card></global-card><local-badge></local-badge></div>
<script>
const globalRegistry = {};
function registerGlobal(name, def) { globalRegistry[name] = def; }
function mountRoot(selector, opts = {}) {
const root = document.querySelector(selector);
const locals = opts.components || {};
const unresolved = [];
Array.from(root.children).forEach(el => {
const tag = el.tagName.toLowerCase();
const def = locals[tag] || globalRegistry[tag];
if (def) {
const wrap = document.createElement('div');
wrap.innerHTML = def.template;
el.replaceWith(wrap.firstElementChild);
} else {
unresolved.push(tag);
}
});
return unresolved;
}
registerGlobal('global-card', { template: '<h1>全局自定义组件!</h1>' });
const LocalBadge = { template: '<span class="badge">局部组件</span>' };
window.__u1 = mountRoot('#app1', { components: { 'local-badge': LocalBadge } });
window.__u2 = mountRoot('#app2');
</script>
</body></html>
""")
actual1 = {
"app1H1": page.locator("#app1 h1").inner_text(),
"app1Badge": page.locator("#app1 .badge").inner_text(),
"app2H1": page.locator("#app2 h1").inner_text(),
"app2BadgeCount": page.locator("#app2 .badge").count(),
"app1Unresolved": page.evaluate("window.__u1"),
"app2Unresolved": page.evaluate("window.__u2"),
}
expected1 = {
"app1H1": "全局自定义组件!",
"app1Badge": "局部组件",
"app2H1": "全局自定义组件!",
"app2BadgeCount": 0,
"app1Unresolved": [],
"app2Unresolved": ["local-badge"],
}
cases.append(make_case("global_and_local_component_registration", expected1, actual1))
# Case 2: static prop + dynamic v-bind prop (one-way parent -> child)
page.set_content("""
<!doctype html>
<html><body>
<div id="static-host"></div>
<input id="parent-input" value="父组件内容">
<div id="dynamic-host"></div>
<script>
function renderChild(host, props) {
const span = document.createElement('span');
span.textContent = props.message;
host.innerHTML = '';
host.appendChild(span);
return Object.freeze({ message: props.message });
}
window.__parentState = { parentMsg: '父组件内容' };
renderChild(document.getElementById('static-host'), { message: 'hello!' });
let childProps = renderChild(document.getElementById('dynamic-host'), { message: window.__parentState.parentMsg });
document.getElementById('parent-input').addEventListener('input', (e) => {
window.__parentState.parentMsg = e.target.value;
childProps = renderChild(document.getElementById('dynamic-host'), { message: window.__parentState.parentMsg });
});
window.__tryMutateChildProp = () => {
let mutated = false;
try { childProps.message = 'child-override'; } catch (_) {}
mutated = (window.__parentState.parentMsg === 'child-override');
return mutated;
};
</script>
</body></html>
""")
static_text = page.locator("#static-host span").inner_text()
initial_dyn = page.locator("#dynamic-host span").inner_text()
page.fill("#parent-input", "父传子动态值")
updated_dyn = page.locator("#dynamic-host span").inner_text()
child_mutated_parent = page.evaluate("window.__tryMutateChildProp()")
actual2 = {
"staticProp": static_text,
"initialDynamic": initial_dyn,
"updatedDynamic": updated_dyn,
"childMutatedParent": child_mutated_parent,
}
expected2 = {
"staticProp": "hello!",
"initialDynamic": "父组件内容",
"updatedDynamic": "父传子动态值",
"childMutatedParent": False,
}
cases.append(make_case("static_and_dynamic_props_binding", expected2, actual2))
# Case 3: v-for rendering todo-item components with bound prop
page.set_content("""
<!doctype html>
<html><body>
<ol id="todo-list"></ol>
<script>
const sites = [{ text: 'HTML' }, { text: 'CSS' }, { text: 'JavaScript' }];
const ol = document.getElementById('todo-list');
sites.forEach(item => {
const li = document.createElement('li');
li.textContent = item.text;
ol.appendChild(li);
});
</script>
</body></html>
""")
actual3 = page.locator("#todo-list li").all_inner_texts()
expected3 = ["HTML", "CSS", "JavaScript"]
cases.append(make_case("v_for_list_props_rendering", expected3, actual3))
# Case 4: Props validation rules (native types, custom constructor, required, default factory, validator)
page.set_content("<!doctype html><html><body></body></html>")
actual4 = page.evaluate("""() => {
class Author { constructor(name) { this.name = name; } }
function checkType(val, ctor) {
if (ctor === String) return typeof val === 'string';
if (ctor === Number) return typeof val === 'number';
if (ctor === Boolean) return typeof val === 'boolean';
if (ctor === Function) return typeof val === 'function';
if (ctor === Symbol) return typeof val === 'symbol';
if (ctor === Array) return Array.isArray(val);
if (ctor === Object) return val !== null && typeof val === 'object' && !Array.isArray(val);
return val instanceof ctor;
}
function validateProp(name, rule, rawVal) {
const spec = (typeof rule === 'function' || Array.isArray(rule)) ? { type: rule } : rule;
let val = rawVal;
if (val === undefined && 'default' in spec) {
val = typeof spec.default === 'function' && spec.type !== Function ? spec.default() : spec.default;
}
if (spec.required && (val === undefined || val === null)) {
return { ok: false, reason: 'missing required prop ' + name };
}
if (val === null || val === undefined) return { ok: true, value: val };
if (spec.type) {
const ctors = Array.isArray(spec.type) ? spec.type : [spec.type];
if (!ctors.some(c => checkType(val, c))) {
return { ok: false, reason: 'type mismatch for ' + name };
}
}
if (spec.validator && !spec.validator(val)) {
return { ok: false, reason: 'validator failed for ' + name };
}
return { ok: true, value: val };
}
const rules = {
propA: Number,
propB: [String, Number],
propC: { type: String, required: true },
propD: { type: Number, default: 100 },
propE: { type: Object, default: () => ({ message: 'hello' }) },
propF: { validator: (v) => ['success', 'warning', 'danger'].includes(v) },
propAuthor: Author,
};
const e1 = validateProp('propE', rules.propE, undefined).value;
const e2 = validateProp('propE', rules.propE, undefined).value;
return {
nullPassesOptionalNumber: validateProp('propA', rules.propA, null).ok,
multiTypeStringOk: validateProp('propB', rules.propB, '42').ok,
missingRequiredC: validateProp('propC', rules.propC, undefined).ok,
defaultD: validateProp('propD', rules.propD, undefined).value,
factoryFreshObjects: e1 !== e2 && e1.message === 'hello',
validatorOk: validateProp('propF', rules.propF, 'warning').ok,
validatorReject: validateProp('propF', rules.propF, 'unknown').ok,
customCtorOk: validateProp('propAuthor', rules.propAuthor, new Author('Vue')).ok,
customCtorReject: validateProp('propAuthor', rules.propAuthor, { name: 'Vue' }).ok,
nativeTypesChecked: [
checkType('a', String), checkType(1, Number), checkType(true, Boolean),
checkType([], Array), checkType({}, Object), checkType(new Date(), Date),
checkType(() => {}, Function), checkType(Symbol('s'), Symbol),
].every(Boolean),
};
}""")
expected4 = {
"nullPassesOptionalNumber": True,
"multiTypeStringOk": True,
"missingRequiredC": False,
"defaultD": 100,
"factoryFreshObjects": True,
"validatorOk": True,
"validatorReject": False,
"customCtorOk": True,
"customCtorReject": False,
"nativeTypesChecked": True,
}
cases.append(make_case("props_validation_rules", expected4, actual4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
如果直接提供对象或数组字面量,所有使用默认值的组件实例会共享同一份内存引用,一个实例修改嵌套属性会连带污染其他实例;通过工厂函数每次返回新对象可保证实例状态隔离。