vue3中怎么调用父组件的方法
时间: 2023-11-03 16:20:55 浏览: 27
在 Vue 3 中,你可以使用 `emit` 方法来调用父组件的方法。以下是一种常见的方式:
在父组件中,定义一个方法,并通过 `v-on` 或简写的 `@` 将该方法绑定到子组件上。例如:
```html
<template>
<div>
<child-component @childMethod="parentMethod"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
parentMethod() {
// 父组件的方法逻辑
}
}
}
</script>
```
在子组件中,通过使用 `this.$emit` 方法,将事件触发到父组件上。例如:
```html
<template>
<button @click="callParentMethod">调用父组件方法</button>
</template>
<script>
export default {
methods: {
callParentMethod() {
this.$emit('childMethod');
}
}
}
</script>
```
当点击子组件中的按钮时,就会触发 `callParentMethod` 方法,并通过 `$emit` 发送 `childMethod` 事件给父组件,最终调用父组件中的 `parentMethod` 方法。
这样,子组件就可以调用父组件的方法了。你可以根据实际情况传递参数给父组件方法或者在父组件中监听更多的事件。