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

vue3调用子组件方法

作者:狂神战天   发布日期:2025-12-31   浏览:82

<template>
  <div>
    <child-component ref="childComponent"></child-component>
    <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>

解释说明

  1. 模板部分 (<template>):

    • 使用 <child-component ref="childComponent"></child-component> 来引入子组件,并通过 ref 属性为子组件创建一个引用。
    • 添加一个按钮,点击时触发 callChildMethod 方法。
  2. 脚本部分 (<script>):

    • 导入 ref 和子组件 ChildComponent
    • setup 函数中定义 childComponent 引用和 callChildMethod 方法。
    • callChildMethod 方法检查子组件是否已挂载,然后调用子组件的 childMethod 方法。
  3. 子组件 (ChildComponent.vue):

    • 子组件中需要有一个名为 childMethod 的方法,可以在其 <script> 部分定义:
      export default {
        methods: {
          childMethod() {
            console.log('子组件方法被调用了');
          }
        }
      };

这样,当点击按钮时,父组件会调用子组件中的 childMethod 方法。

上一篇:vue json 编辑器

下一篇:vue获取时间戳

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

vue3组件传值的方式

vue3 子路由

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

Laravel 中文站