Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue自定义事件

作者:淺墨   发布日期:2026-05-03   浏览:89

// 父组件 ParentComponent.vue
<template>
  <div>
    <child-component @custom-event="handleCustomEvent"></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    handleCustomEvent(payload) {
      console.log('Custom event triggered with payload:', payload);
    }
  }
};
</script>

// 子组件 ChildComponent.vue
<template>
  <div>
    <button @click="triggerCustomEvent">Trigger Custom Event</button>
  </div>
</template>

<script>
export default {
  methods: {
    triggerCustomEvent() {
      // 触发自定义事件,并传递一个负载(payload)
      this.$emit('custom-event', { message: 'Hello from child component!' });
    }
  }
};
</script>

解释说明:

  1. 父组件 (ParentComponent.vue):

    • 使用 <child-component> 标签引入子组件。
    • 监听子组件的自定义事件 @custom-event,并通过 handleCustomEvent 方法处理该事件。
    • 当子组件触发 custom-event 时,handleCustomEvent 方法会被调用,并接收子组件传递的负载(payload)。
  2. 子组件 (ChildComponent.vue):

    • 包含一个按钮,点击按钮时会调用 triggerCustomEvent 方法。
    • triggerCustomEvent 方法通过 this.$emit 触发名为 custom-event 的自定义事件,并传递一个负载对象 { message: 'Hello from child component!' } 给父组件。

通过这种方式,父组件可以监听子组件的自定义事件,并根据事件传递的数据进行相应的处理。

上一篇:vue3使用nexttick

下一篇:vue可编辑表格

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站