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

vue3子组件调用父组件方法

作者:依寞相随   发布日期:2025-07-14   浏览:17

// 父组件 ParentComponent.vue
<template>
  <div>
    <h1>父组件</h1>
    <ChildComponent @child-event="parentMethod" />
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    parentMethod(message) {
      console.log('父组件方法被调用:', message);
    }
  }
};
</script>

// 子组件 ChildComponent.vue
<template>
  <div>
    <h2>子组件</h2>
    <button @click="callParentMethod">调用父组件方法</button>
  </div>
</template>

<script>
export default {
  methods: {
    callParentMethod() {
      // 使用 $emit 触发自定义事件,传递参数给父组件
      this.$emit('child-event', '来自子组件的消息');
    }
  }
};
</script>

解释说明

  1. 父组件 (ParentComponent.vue):

    • 在模板中引入了子组件 ChildComponent
    • 使用 @child-event="parentMethod" 监听来自子组件的自定义事件 child-event,当该事件触发时,会调用父组件中的 parentMethod 方法。
  2. 子组件 (ChildComponent.vue):

    • 包含一个按钮,点击按钮时会调用 callParentMethod 方法。
    • callParentMethod 方法通过 this.$emit('child-event', '来自子组件的消息') 发出一个名为 child-event 的自定义事件,并传递一个消息给父组件。
    • 父组件监听到这个事件后,会执行对应的处理逻辑,即调用 parentMethod 方法并接收传递过来的消息。

上一篇:vue getcurrentinstance

下一篇:vue.config

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

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

Laravel 中文站