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

vue父组件调用子组件方法

作者:伱的精力病康复了?   发布日期:2025-04-28   浏览:98

// 父组件 ParentComponent.vue
<template>
  <div>
    <button @click="callChildMethod">调用子组件方法</button>
    <ChildComponent ref="childComponent" />
  </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. 父组件 (ParentComponent.vue) 中使用了 <ChildComponent>,并通过 ref 属性给子组件指定了一个引用名称 childComponent
  2. 在父组件的 methods 中定义了一个 callChildMethod 方法,该方法通过 this.$refs.childComponent 获取到子组件实例,并调用其 childMethod 方法。
  3. 子组件 (ChildComponent.vue) 中定义了一个 childMethod 方法,当父组件调用时会执行相应的逻辑(例如打印一条消息)。

这种方式可以实现父组件调用子组件中的方法。

上一篇:vue 路由跳转

下一篇:vue component

大家都在看

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