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

vue3 子组件调用父组件的方法

作者:—上花′Ing   发布日期:2025-04-14   浏览:73

<template>
  <div>
    <!-- 父组件 -->
    <parent-component>
      <child-component @custom-event="handleEvent"></child-component>
    </parent-component>
  </div>
</template>

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

export default {
  components: {
    ParentComponent,
    ChildComponent
  },
  methods: {
    handleEvent(data) {
      console.log('父组件的方法被调用了', data);
    }
  }
};
</script>
<!-- ChildComponent.vue -->
<template>
  <button @click="callParentMethod">点击调用父组件方法</button>
</template>

<script>
export default {
  methods: {
    callParentMethod() {
      this.$emit('custom-event', '子组件传递的数据');
    }
  }
};
</script>

解释说明:

  1. 父组件:在父组件中,我们通过 v-on 指令监听子组件发出的自定义事件 (@custom-event),并将父组件的方法 (handleEvent) 绑定到该事件上。
  2. 子组件:在子组件中,我们通过 $emit 方法触发自定义事件 (custom-event),并将数据传递给父组件。当用户点击按钮时,子组件会调用 callParentMethod 方法,进而触发父组件的 handleEvent 方法。

这种方式是 Vue.js 中常用的父子组件通信方式之一。

上一篇:使用vite创建vue3项目

下一篇:vue字符串转json对象

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

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

Laravel 中文站