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

vue3父组件调用子组件方法

作者:风中孤狼   发布日期:2026-05-26   浏览:21

// 父组件 ParentComponent.vue
<template>
  <div>
    <ChildComponent ref="childComponent" />
    <button @click="callChildMethod">调用子组件方法</button>
  </div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  setup() {
    const childComponent = ref(null);

    const callChildMethod = () => {
      if (childComponent.value) {
        childComponent.value.childMethod();
      }
    };

    return {
      childComponent,
      callChildMethod
    };
  }
};
</script>

// 子组件 ChildComponent.vue
<template>
  <div>
    <!-- 子组件内容 -->
  </div>
</template>

<script>
export default {
  methods: {
    childMethod() {
      console.log('子组件的方法被调用了');
    }
  }
};
</script>

解释说明

  1. 父组件 (ParentComponent.vue):

    • 使用 ref 来引用子组件实例 (ChildComponent)。
    • 定义了一个按钮,点击时调用 callChildMethod 方法。
    • callChildMethod 方法通过 childComponent.value.childMethod() 调用子组件的 childMethod 方法。
  2. 子组件 (ChildComponent.vue):

    • 定义了一个 methods 属性中的 childMethod 方法。
    • 当父组件调用该方法时,会在控制台输出一条消息。

这种方式利用了 Vue 3 的组合式 API 和 ref 特性,使得父组件可以方便地调用子组件的方法。

上一篇:vue3 计算属性

下一篇:vue foreach

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

vue.js 3

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js devserv

vue.config.js configu

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

Laravel 中文站