vue3 setup 父页面调用子组件中方法
时间: 2023-08-25 15:03:31 浏览: 64
在 Vue 3 中,使用 `setup` 语法糖时,父组件可以通过 `ref` 或 `reactive` 创建一个响应式对象,然后将子组件的方法添加到该对象中,以便在父组件中调用子组件的方法。
以下是一个示例:
```javascript
// 子组件 ChildComponent.vue
<template>
<div>
<button @click="childMethod">子组件方法</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
// 子组件的方法逻辑
}
}
};
</script>
```
```javascript
// 父组件 ParentComponent.vue
<template>
<div>
<ChildComponent :childMethod="childMethod" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const childMethod = ref(null); // 创建一个响应式对象
const callChildMethod = () => {
if (childMethod.value) {
childMethod.value(); // 在父组件中调用子组件的方法
}
};
return {
childMethod,
callChildMethod
};
}
};
</script>
```
在父组件的 `setup` 函数中,我们创建了一个 `childMethod` 的响应式对象,并将其传递给子组件。然后,我们在父组件中定义了一个 `callChildMethod` 的方法,当点击父组件中的按钮时,会调用子组件中的方法。
注意:在父组件中调用子组件的方法时,需要判断 `childMethod.value` 是否存在,以避免在初始化阶段调用未定义的方法。
这样,当在父组件中点击 "调用子组件方法" 的按钮时,会触发子组件中的 `childMethod` 方法。