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

vue3 父组件调用子组件的方法

作者:_永恒灬莫言   发布日期:2025-08-05   浏览:87

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

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
      // 使用 this.$refs 来访问子组件实例,并调用其方法
      this.$refs.childComponent.childMethod();
    }
  }
};
</script>

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

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

解释说明:

  1. 父组件:在父组件中,我们通过 ref 属性给子组件起一个引用名(如 childComponent),然后可以通过 this.$refs.childComponent 访问到子组件的实例。
  2. 调用子组件方法:当点击按钮时,触发 callChildMethod 方法,该方法通过 this.$refs.childComponent.childMethod() 调用子组件中的 childMethod 方法。
  3. 子组件:子组件中定义了一个普通的方法 childMethod,它会在被父组件调用时执行。

上一篇:vue3 全局方法

下一篇: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 中文站