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

vue this.$emit

作者:千山暮雪ミ   发布日期:2026-04-08   浏览:97

// 父组件
<template>
  <div>
    <ChildComponent @custom-event="handleCustomEvent" />
  </div>
</template>

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

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

// 子组件 (ChildComponent.vue)
<template>
  <div>
    <button @click="emitCustomEvent">Emit Custom Event</button>
  </div>
</template>

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

解释说明

  1. 父组件:在父组件中,我们通过 @custom-event 监听子组件触发的自定义事件,并在事件触发时调用 handleCustomEvent 方法。
  2. 子组件:在子组件中,我们定义了一个按钮,当点击按钮时会调用 emitCustomEvent 方法。该方法使用 this.$emit 来触发一个名为 custom-event 的自定义事件,并传递一个对象作为参数。
  3. 事件传递:当子组件中的按钮被点击时,custom-event 事件会被触发,父组件中相应的处理函数 handleCustomEvent 会被调用,并接收到子组件传递的参数。

这种方式使得父组件可以监听子组件的状态变化或用户交互,从而实现父子组件之间的通信。

上一篇:ant design vue3

下一篇:vue3 router.push

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

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

Laravel 中文站