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

vue 调用子组件方法

作者:冷空气来袭   发布日期:2025-05-15   浏览:29

<template>
  <div>
    <child-component ref="childComponent"></child-component>
    <button @click="callChildMethod">调用子组件方法</button>
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    callChildMethod() {
      this.$refs.childComponent.childMethod();
    }
  }
};
</script>

解释说明:

  1. 父组件:在父组件中,我们通过 ref 属性为子组件 (ChildComponent) 设置了一个引用名称 (childComponent)。
  2. 按钮点击事件:当用户点击按钮时,会触发 callChildMethod 方法。
  3. 调用子组件方法:在 callChildMethod 方法中,通过 this.$refs.childComponent 获取到子组件实例,然后调用子组件中的 childMethod 方法。

子组件 (ChildComponent.vue) 示例代码:

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

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

子组件解释:

  1. 定义方法:在子组件中定义了一个名为 childMethod 的方法,该方法会在父组件调用时执行,并输出一条日志信息。

上一篇:vue3 动态style

下一篇:vue父组件如何向子组件中传递数据

大家都在看

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