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

vue3 父组件调用子组件方法

作者:望断天涯   发布日期:2025-10-06   浏览:42

// 父组件调用子组件方法的示例代码

// 子组件 ChildComponent.vue
<template>
  <div>
    <p>这是子组件</p>
  </div>
</template>

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

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

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

export default {
  name: 'ParentComponent',
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
      this.$refs.childComponent.childMethod(); // 通过 ref 调用子组件的方法
    }
  }
}
</script>

解释说明:

  1. 子组件 (ChildComponent.vue):

    • 定义了一个简单的子组件,其中包含一个名为 childMethod 的方法。这个方法会在控制台打印一条消息。
  2. 父组件 (ParentComponent.vue):

    • 在父组件中,通过 ref 属性为子组件指定了一个引用名称(ref="childComponent")。
    • 父组件中定义了一个按钮,点击按钮时会调用 callChildMethod 方法。
    • callChildMethod 方法通过 this.$refs.childComponent.childMethod() 调用了子组件中的 childMethod 方法。

通过这种方式,父组件可以成功调用子组件中的方法。

上一篇:vue :style

下一篇:vue3 setup

大家都在看

vue js for循环

vue.config.js 配置

vue.config.js configu

node.js vue

vue3组件传值的方式

vue 图表组件

vue3+vite+ts

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

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

Laravel 中文站