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

vue3 调用子组件方法

作者:ンц枫飄落   发布日期:2025-03-16   浏览:335

// 父组件 ParentComponent.vue

<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>

// 子组件 ChildComponent.vue

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

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

解释说明:

  1. 父组件 (ParentComponent.vue):

    • 使用 ref 来引用子组件 (ChildComponent)。
    • 在按钮点击事件中,通过 childComponent.value.childMethod() 调用子组件的方法。
  2. 子组件 (ChildComponent.vue):

    • 定义了一个方法 childMethod,该方法会在父组件调用时执行。
  3. 关键点:

    • ref 是 Vue 3 中用于获取对 DOM 元素或子组件实例的引用的关键字。
    • 通过 ref 获取子组件实例后,可以直接调用其上的方法。

上一篇:vue项目打包

下一篇:vue antd

大家都在看

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