学习优先度:★★★★☆
难易度:★★★☆☆
Vue 组件可发出自定义事件与父组件通信,从而实现灵活的解耦组件设计。
下面的示例演示了 Vue 组件如何向其父组件发出自定义事件。
【代码示例】
<!-- ParentComponent.vue -->
<template>
<div>
<ChildComponent @custom-event="handleCustomEvent"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleCustomEvent(data) {
console.log(data); // Log the data received from the child component
}
}
};
</script>
vue
<!-- ChildComponent.vue -->
<template>
<div>
<button @click="emitEvent">Emit Event</button>
</div>
</template>
<script>
export default {
methods: {
emitEvent() {
this.$emit('custom-event', { message: 'Event from ChildComponent', timestamp: Date.now() });
// Emit a custom event with a data object
}
}
};
</script>
【执行结果】
当 `ChildComponent` 中的按钮被点击时,父组件将向控制台记录一个包含消息和时间戳的对象。
使用 this.$emit,您可以从 Vue 组件发出任何自定义事件。这对于创建可重用的模块化组件特别有用,因为它允许你定义组件的通信方式,而无需将它们紧密耦合在一起。发出的事件可以携带数据,因此适用于各种用例。
【补充】
this.$emit 方法可用于从同一组件中发出多个自定义事件。Vue 的自定义事件系统通过促进清晰的关注点分离,增强了基于组件的架构。