Vue.js 组件 - 自定义事件
核对组件间 $on/$emit 自定义事件、.native 原生事件监听、data 必须为函数的原因,以及自定义组件 v-model 与 model 选项。
学完这一章,你能够
- 核对组件间 $on/$emit 自定义事件、.native 原生事件监听、data 必须为函数的原因,以及自定义组件 v-model 与 model 选项。
子传父自定义事件与 .native 修饰符
父组件通过 `props` 向子组件下发数据,子组件向父组件回传通知则依赖自定义事件。每个 Vue 实例均实现事件接口:`$on(eventName)` 监听事件,`$emit(eventName)` 触发事件;父组件可在子组件标签上直接以 `v-on` 监听子组件抛出的内部事件,使子组件与外部逻辑解耦。若需直接在组件根元素上监听原生 DOM 事件,可使用 `.native` 修饰符(如 `v-on:click.native`)。本站离线 Chromium 实测两个 `<button-counter>` 实例分别点击 2 次与 1 次,各自局部计数为 `[2, 1]`,父级汇总 `total` 累加为 `3`,且根元素 `.native` 点击记录为 `1`。
组件 data 必须为函数
可复用组件的 `data` 必须写成返回新对象的函数,从而让每个组件实例维护一份独立状态拷贝;若多个实例返回同一个外部共享对象,任一实例的修改都会同步影响其余实例。本站离线 Chromium 对比挂载 3 个按钮实例并点击第 1 个:独立函数工厂组计数为 `[1, 0, 0]`,共享对象组则全部联动为 `[1, 1, 1]`。
自定义组件的 v-model 与 model 选项
组件上的 `v-model` 本质是语法糖,默认绑定名为 `value` 的 prop 并监听名为 `input` 的自定义事件(即 `<input v-model="parentData">` 等价于 `:value="parentData" @input="parentData = $event.target.value"`)。自定义输入组件只需接收 `props: ['value']` 并在内部输入时 `$emit('input', $event.target.value)`,即可与父组件双向同步。本站离线 Chromium 实测初始 `num` 为 `100`,子输入框改写为 `256` 后父视图即时刷新为“输入的数字为:256”。
对于复选框或单选框等原生依赖 `checked` 属性与 `change` 事件的组件,可在组件中声明 `model: { prop: 'checked', event: 'change' }` 覆写默认协议,再显式声明 `checked: Boolean` prop 并在 `change` 时 `$emit('change', $event.target.checked)`。本站离线 Chromium 实测 `lovingVue` 初始为 `true` 时关联区域 `display` 为 `block`,取消勾选后同步变为 `false` 且区域隐藏为 `none`,重新勾选后恢复 `block`。
离线 Chromium 验证自定义事件、data 隔离与组件 v-model
"""Offline Chromium runtime verification for Vue 2 Chapter 14: vue-component-custom-event."""
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: $on / $emit child-to-parent custom event + .native root event
page.set_content("""
<!doctype html>
<html><body>
<p id="total">0</p>
<div id="counters"></div>
<div id="native-comp"><button id="native-root">Native Root</button></div>
<script>
class EventBus {
constructor() { this.map = {}; }
$on(evt, fn) { (this.map[evt] = this.map[evt] || []).push(fn); }
$emit(evt, ...args) { (this.map[evt] || []).forEach(fn => fn(...args)); }
}
window.__parent = { total: 0, nativeHits: 0 };
function createButtonCounter(id) {
const bus = new EventBus();
const state = { counter: 0 };
const btn = document.createElement('button');
btn.id = id;
btn.textContent = '0';
btn.addEventListener('click', () => {
state.counter += 1;
btn.textContent = String(state.counter);
bus.$emit('increment');
});
bus.$on('increment', () => {
window.__parent.total += 1;
document.getElementById('total').textContent = String(window.__parent.total);
});
document.getElementById('counters').appendChild(btn);
}
createButtonCounter('bc1');
createButtonCounter('bc2');
// .native binds directly to root element
document.getElementById('native-root').addEventListener('click', () => {
window.__parent.nativeHits += 1;
});
</script>
</body></html>
""")
page.click("#bc1")
page.click("#bc1")
page.click("#bc2")
page.click("#native-root")
actual1 = {
"bc1": int(page.locator("#bc1").inner_text()),
"bc2": int(page.locator("#bc2").inner_text()),
"total": int(page.locator("#total").inner_text()),
"nativeHits": page.evaluate("window.__parent.nativeHits"),
}
expected1 = {"bc1": 2, "bc2": 1, "total": 3, "nativeHits": 1}
cases.append(make_case("child_emit_and_parent_on", expected1, actual1))
# Case 2: data must be a function (isolated copies vs shared object pollution)
page.set_content("""
<!doctype html>
<html><body>
<div id="isolated"></div>
<div id="shared"></div>
<script>
function mountCounters(containerId, dataFactory) {
const host = document.getElementById(containerId);
const instances = [];
for (let i = 0; i < 3; i++) {
const state = dataFactory();
const btn = document.createElement('button');
btn.id = containerId + '-' + i;
const render = () => { btn.textContent = String(state.count); };
render();
instances.push({ state, render });
btn.addEventListener('click', () => {
state.count += 1;
instances.forEach(inst => inst.render());
});
host.appendChild(btn);
}
}
mountCounters('isolated', () => ({ count: 0 }));
const sharedObj = { count: 0 };
mountCounters('shared', () => sharedObj);
</script>
</body></html>
""")
page.click("#isolated-0")
page.click("#shared-0")
actual2 = {
"isolated": [int(x) for x in page.locator("#isolated button").all_inner_texts()],
"shared": [int(x) for x in page.locator("#shared button").all_inner_texts()],
}
expected2 = {"isolated": [1, 0, 0], "shared": [1, 1, 1]}
cases.append(make_case("data_function_vs_shared_object", expected2, actual2))
# Case 3: custom component default v-model (value prop + input event)
page.set_content("""
<!doctype html>
<html><body>
<p><input id="custom-num" value="100"></p>
<p id="parent-num">输入的数字为:100</p>
<script>
window.__numModel = 100;
document.getElementById('custom-num').addEventListener('input', (e) => {
// Equivalent to $emit('input', $event.target.value)
window.__numModel = e.target.value;
document.getElementById('parent-num').textContent = '输入的数字为:' + window.__numModel;
});
</script>
</body></html>
""")
initial_num = page.locator("#parent-num").inner_text()
page.fill("#custom-num", "256")
actual3 = {
"initial": initial_num,
"updated": page.locator("#parent-num").inner_text(),
"modelValue": page.evaluate("window.__numModel"),
}
expected3 = {
"initial": "输入的数字为:100",
"updated": "输入的数字为:256",
"modelValue": "256",
}
cases.append(make_case("custom_component_v_model_default", expected3, actual3))
# Case 4: custom component model option ({ prop: 'checked', event: 'change' })
page.set_content("""
<!doctype html>
<html><body>
<input type="checkbox" id="base-cb" checked>
<div id="love-box">如果选择框打勾我就会显示。</div>
<script>
window.__lovingVue = true;
const cb = document.getElementById('base-cb');
const box = document.getElementById('love-box');
function sync() {
cb.checked = window.__lovingVue;
box.style.display = window.__lovingVue ? 'block' : 'none';
}
sync();
cb.addEventListener('change', (e) => {
// Equivalent to $emit('change', $event.target.checked)
window.__lovingVue = e.target.checked;
sync();
});
</script>
</body></html>
""")
init_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
page.uncheck("#base-cb")
after_uncheck_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
after_uncheck_val = page.evaluate("window.__lovingVue")
page.check("#base-cb")
after_recheck_disp = page.evaluate("getComputedStyle(document.getElementById('love-box')).display")
actual4 = {
"initialDisplay": init_disp,
"afterUncheckDisplay": after_uncheck_disp,
"afterUncheckModel": after_uncheck_val,
"afterRecheckDisplay": after_recheck_disp,
}
expected4 = {
"initialDisplay": "block",
"afterUncheckDisplay": "none",
"afterUncheckModel": False,
"afterRecheckDisplay": "block",
}
cases.append(make_case("custom_component_model_option", expected4, actual4))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 $emit 汇总计数与 .native 触发、独立工厂 [1,0,0] 与共享对象 [1,1,1] 对比、默认 value/input 双向同步及 model 选项 checked/change 切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:fcbe825f3b10e050b6e0b0fd7fc41ebc5da18b7e880368c9c2ce8205094c774c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:29018cf46bd2dcdb0dbd617d66b34922509322c22dc1e889612e0ef215c237eb
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Vue 2 中封装自定义复选框组件支持 `v-model` 时,为什么需要配置 `model` 选项?
展开参考解答
因为组件上的 `v-model` 默认绑定 `value` prop 与 `input` 事件,而复选框应使用 `checked` 布尔属性和 `change` 事件;通过 `model: { prop: 'checked', event: 'change' }` 即可将 `v-model` 正确映射到复选框语义。