vue3使用父组件方法
时间: 2023-11-03 14:22:36 浏览: 39
在 Vue 3 中,你可以通过 props 将父组件的方法传递给子组件,然后在子组件中调用父组件的方法。下面是一个示例:
```vue
<template>
<div>
<button @click="callParentMethod">调用父组件方法</button>
</div>
</template>
<script>
export default {
props: {
parentMethod: {
type: Function,
required: true
}
},
methods: {
callParentMethod() {
// 调用父组件传递的方法
this.parentMethod();
}
}
}
</script>
```
在父组件中,你可以将父组件的方法作为 prop 传递给子组件:
```vue
<template>
<div>
<child-component :parentMethod="parentMethod"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
parentMethod() {
// 这里是父组件的方法
console.log('父组件的方法被调用了'); }
}
}
</script>
```
这样,当在子组件中点击按钮时,就会调用父组件的方法。