vue3 父组建调用子组建的方法
时间: 2024-02-28 20:50:56 浏览: 14
在Vue 3中,父组件可以通过使用`ref`或`reactive`来创建一个响应式的子组件引用,并通过`.value`来访问子组件的方法。下面是一个示例:
```javascript
// 子组件
const ChildComponent = {
methods: {
childMethod() {
console.log("子组件的方法被调用了");
},
},
};
// 父组件
const ParentComponent = {
setup() {
// 创建一个响应式的子组件引用
const childRef = ref(null);
// 在子组件被挂载后,将子组件实例赋值给子组件引用
const onChildMounted = (childInstance) => {
childRef.value = childInstance;
};
// 父组件调用子组件的方法
const callChildMethod = () => {
childRef.value.childMethod();
};
return {
onChildMounted,
callChildMethod,
};
},
template: `
<div>
<child-component @mounted="onChildMounted"></child-component>
<button @click="callChildMethod">调用子组件方法</button>
</div>
`,
};
```
在上面的示例中,父组件通过`ref`创建了一个响应式的子组件引用`childRef`。当子组件被挂载后,通过`@mounted`事件将子组件实例赋值给`childRef.value`。然后,父组件可以通过调用`childRef.value.childMethod()`来调用子组件的方法。