// 子组件 (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>
子组件 (ChildComponent.vue
):
emits
选项定义了可以触发的事件 customEvent
。emitCustomEvent
中,通过 this.$emit('customEvent', '这是从子组件传递的数据')
触发了 customEvent
事件,并传递了一个字符串作为参数。父组件 (ParentComponent.vue
):
<child-component>
并绑定了 @customEvent
事件监听器。customEvent
时,父组件中的 handleCustomEvent
方法会被调用,并接收到子组件传递的数据。上一篇:vue3 全局方法
下一篇:vue3 父组件调用子组件的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站