学习优先度:★★★★★

难易度:★★★★☆

自定义事件允许子组件与父组件通信。

VueJS 中的自定义事件用于将数据从子组件发送回父组件,从而促进双向通信。

【代码示例】

// ParentComponent.vue
<template>
  <div>
  <ChildComponent @customEvent="handleCustomEvent" />
 </div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
 components: {
  ChildComponent
 },
 methods: {
  handleCustomEvent(data) {
   console.log('Received from child:', data);
  }
 }
};
</script>
// ChildComponent.vue
<template>
  <div>
  <button @click="emitCustomEvent">Click me</button>
 </div>
</template>
<script>
export default {
 methods: {
  emitCustomEvent() {
   this.$emit('customEvent', 'Hello from Child!');
  }
 }
};
</script>

【执行结果】

Received from child: Hello from Child!

在本示例中,当点击按钮时,ChildComponent 会发出一个包含数据的自定义事件(customEvent)。父组件使用 @customEvent=“handleCustomEvent ”监听该事件,并使用 handleCustomEvent 方法处理该事件,同时记录接收到的数据。

【补充】

自定义事件可以传递多个参数,甚至是复杂的数据结构。它们是管理组件间通信的强大方法,尤其是在大型应用程序中。