vue3setup父调用子组件方法
时间: 2023-11-03 14:18:00 浏览: 37
在 Vue 3 中,你可以通过 `ref` 和 `emit` 来实现父组件调用子组件的方法。
首先,在子组件中定义一个方法,并将其暴露为可访问的属性。例如,在子组件的 `<script>` 标签中:
```vue
<script>
import { ref } from "vue";
export default {
setup(props, context) {
const childMethod = () => {
console.log("子组件方法被调用");
};
// 将子组件方法暴露给父组件
context.expose({ childMethod });
return {
// ...
};
},
};
</script>
```
然后,在父组件中,可以通过 `ref` 来获取子组件的实例,并调用其暴露的方法。例如:
```vue
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { ref } from "vue";
import ChildComponent from "./ChildComponent.vue";
export default {
components: {
ChildComponent,
},
setup() {
const childRef = ref(null);
const callChildMethod = () => {
if (childRef.value) {
childRef.value.childMethod();
}
};
return {
childRef,
callChildMethod,
};
},
};
</script>
```
在上面的例子中,使用 `ref` 创建了一个 `childRef` 引用,然后将其赋值给子组件的 `ref` 属性。然后,在父组件的 `callChildMethod` 方法中,通过 `childRef.value` 获取子组件的实例,并调用其暴露的方法 `childMethod()`。
这样,当父组件的按钮被点击时,就会调用子组件的方法。请注意,这里需要在子组件上使用 `ref` 属性,并使用 `.value` 来获取子组件的实例。