vue3父调用子组件方法
时间: 2023-08-22 12:05:33 浏览: 106
在 Vue 3 中,父组件可以通过 `ref` 或 `reactive` 创建一个引用,然后将其传递给子组件,从而可以调用子组件的方法。下面是一个示例:
在父组件中:
```vue
<template>
<div>
<button @click="callChildMethod">调用子组件方法</button>
<child-component :childRef="childRef"></child-component>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
// 创建一个 ref 引用
const childRef = ref(null);
// 父组件调用子组件方法
const callChildMethod = () => {
if (childRef.value) {
childRef.value.childMethod();
}
};
return {
childRef,
callChildMethod
};
}
};
</script>
```
在子组件中:
```vue
<template>
<div>
<p>子组件</p>
</div>
</template>
<script>
export default {
setup(props) {
// 子组件方法
const childMethod = () => {
console.log('子组件方法被调用');
};
return {
childMethod
};
}
};
</script>
```
在上面的示例中,父组件通过 `ref` 创建了一个引用 `childRef`,然后将其传递给子组件 `ChildComponent`。父组件中的 `callChildMethod` 方法可以通过 `childRef.value` 来访问子组件的方法 `childMethod`,从而实现了父组件调用子组件方法的功能。
阅读全文
相关推荐











