vue3父组件将方法传给子组件
时间: 2023-08-25 10:15:30 浏览: 54
在Vue 3中,你可以通过属性传递将父组件的方法传递给子组件。下面是一个示例:
在父组件中,定义一个方法并将其传递给子组件:
```vue
<template>
<div>
<ChildComponent :childMethod="parentMethod" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
parentMethod() {
// 父组件的方法逻辑
}
}
}
</script>
```
在子组件中,接收父组件传递的方法并使用它:
```vue
<template>
<div>
<button @click="childMethod">调用父组件方法</button>
</div>
</template>
<script>
export default {
props: {
childMethod: {
type: Function,
required: true
}
},
methods: {
childMethod() {
this.childMethod(); // 调用父组件传递的方法
}
}
}
</script>
```
在父组件中,使用`ChildComponent`时,通过`childMethod`属性将父组件的方法传递给子组件。在子组件中,接收该属性并将其作为自己的方法来调用。这样,当子组件中的按钮被点击时,就会触发父组件中的方法。