学习优先度:★★★★☆

难易度:★★★☆☆

Vue 的 v-on 指令可用于处理应用程序中的自定义事件。这样,组件之间就可以通过您定义的事件进行通信。

下面是一个示例,父组件监听来自子组件的名为 custom-event 的自定义事件。

【代码示例】

<!-- ParentComponent.vue -->
<template>
  <div>
  <ChildComponent @custom-event="handleCustomEvent"></ChildComponent>
 </div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
 components: {
  ChildComponent
 },
 methods: {
  handleCustomEvent(message) {
   alert(message); // Display the message from the child component
  }
 }
};
</script>
vue
<!-- ChildComponent.vue -->
<template>
  <div>
  <button @click="emitCustomEvent">Click me to emit custom event</button>
 </div>
</template>
<script>
export default {
 methods: {
  emitCustomEvent() {
   this.$emit('custom-event', 'Hello from ChildComponent!'); // Emit the custom event with a message
  }
 }
};
</script>

【执行结果】

当点击 ChildComponent 中的按钮时,父组件中将显示一个提示框,提示信息为 “Hello from ChildComponent!”。

在 Vue 中,v-on 是一个用于监听 DOM 事件的指令。您还可以用它来监听子组件发出的自定义事件。@custom-event="handleCustomEvent" 语法是 v-on:custom-event="handleCustomEvent" 的简写。子组件中的 this.$emit 方法会触发自定义事件,并将任何其他参数传递给父组件的事件处理程序。

【补充】

自定义事件对于组件之间的通信非常有用,尤其是在大型应用程序中,仅通过道具传递数据会变得非常麻烦。Vue 的事件系统受到 DOM 事件系统的启发,对于熟悉网络开发的人来说非常直观。