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

vue 子组件调用父组件方法

作者:涅盘の梦   发布日期:2026-04-06   浏览:101

// 父组件 ParentComponent.vue
<template>
  <div>
    <child-component @custom-event="parentMethod"></child-component>
  </div>
</template>

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

export default {
  components: {
    ChildComponent
  },
  methods: {
    parentMethod() {
      console.log('Parent method called');
    }
  }
};
</script>

// 子组件 ChildComponent.vue
<template>
  <div>
    <button @click="callParentMethod">Call Parent Method</button>
  </div>
</template>

<script>
export default {
  methods: {
    callParentMethod() {
      this.$emit('custom-event');
    }
  }
};
</script>

解释说明:

  1. 父组件 (ParentComponent.vue):

    • 在模板中使用子组件 <child-component>,并通过 @custom-event="parentMethod" 监听子组件发出的自定义事件。
    • 定义了一个方法 parentMethod,当子组件触发 custom-event 时,这个方法会被调用。
  2. 子组件 (ChildComponent.vue):

    • 包含一个按钮,点击按钮时调用 callParentMethod 方法。
    • callParentMethod 方法通过 this.$emit('custom-event') 触发一个自定义事件 custom-event,通知父组件调用其方法。

通过这种方式,子组件可以通过事件机制调用父组件的方法。

上一篇:vue3 created方法

下一篇:vue3 emit用法

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

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

Laravel 中文站