vue3父组件如何操作子组件方法
时间: 2023-08-18 12:13:34 浏览: 81
在Vue 3中,父组件可以通过`ref`或`$refs`来访问和操作子组件的方法。下面是一个示例,演示了父组件如何操作子组件的方法:
首先,在子组件中,我们需要使用`ref`将方法暴露给父组件:
```vue
<template>
<div>
<button @click="childMethod">子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const childMethod = () => {
// 子组件方法逻辑
};
// 将子组件方法暴露给父组件
const exposedMethod = ref(childMethod);
return {
childMethod,
exposedMethod,
};
},
};
</script>
```
然后,在父组件中,我们可以通过`$refs`来访问到子组件实例,并调用其暴露的方法:
```vue
<template>
<div>
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
export default {
methods: {
callChildMethod() {
this.$refs.childComponent.exposedMethod(); // 调用子组件的方法
},
},
};
</script>
```
在上述示例中,父组件通过`$refs`获取子组件实例,并调用其暴露的方法`exposedMethod()`。这样就实现了父组件操作子组件方法的功能。