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

vue3 ref调用子组件方法

作者:蛋蛋的憂傷   发布日期:2025-07-23   浏览:67

<template>
  <div>
    <ChildComponent ref="childComponent" />
    <button @click="callChildMethod">Call Child Method</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. 模板部分

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

    • 使用 ref 创建一个响应式的引用 childComponent,用于存储子组件的实例。
    • 定义 callChildMethod 方法,该方法会检查 childComponent.value 是否存在,如果存在则调用子组件中的 childMethod 方法。
    • 最后将 childComponentcallChildMethod 返回,使其可以在模板中使用。
  3. 子组件(ChildComponent.vue)

    • 子组件需要定义一个方法 childMethod,这个方法会在父组件中被调用。

子组件示例代码:

<template>
  <div>
    <!-- 子组件的内容 -->
  </div>
</template>

<script>
export default {
  methods: {
    childMethod() {
      console.log('Child method called');
    }
  }
};
</script>

上一篇:vue.global.js

下一篇:vue样式

大家都在看

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 中文站