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

vue3 emits

作者:刀魂使者   发布日期:2025-10-09   浏览:70

// 子组件 (ChildComponent.vue)
<template>
  <button @click="emitCustomEvent">点击我</button>
</template>

<script>
export default {
  name: 'ChildComponent',
  emits: ['customEvent'], // 定义可以触发的事件
  methods: {
    emitCustomEvent() {
      this.$emit('customEvent', '这是从子组件传递的数据'); // 触发自定义事件并传递数据
    }
  }
}
</script>

// 父组件 (ParentComponent.vue)
<template>
  <child-component @customEvent="handleCustomEvent"></child-component>
</template>

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

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  methods: {
    handleCustomEvent(data) {
      console.log('收到子组件传递的数据:', data); // 处理子组件传递的数据
    }
  }
}
</script>

解释说明:

  1. 子组件 (ChildComponent.vue):

    • 使用 emits 选项定义了可以触发的事件 customEvent
    • 在方法 emitCustomEvent 中,通过 this.$emit('customEvent', '这是从子组件传递的数据') 触发了 customEvent 事件,并传递了一个字符串作为参数。
  2. 父组件 (ParentComponent.vue):

    • 在模板中使用了子组件 <child-component> 并绑定了 @customEvent 事件监听器。
    • 当子组件触发 customEvent 时,父组件中的 handleCustomEvent 方法会被调用,并接收到子组件传递的数据。

上一篇:vue3 全局方法

下一篇:vue3 父组件调用子组件的方法

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

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

Laravel 中文站