vue3 +ts 父组件调用子组件方法
时间: 2023-06-21 08:09:12 浏览: 123
在 Vue3 + TypeScript 中,可以通过 `ref` 和 `setup()` 函数来实现父子组件之间的方法调用。
首先,在子组件中,需要使用 `defineExpose` 方法将需要暴露给父组件的方法暴露出来:
```typescript
import { defineComponent, defineExpose } from 'vue';
export default defineComponent({
setup() {
const foo = () => {
console.log('foo');
};
const bar = () => {
console.log('bar');
};
// 将 foo 和 bar 方法暴露给父组件
defineExpose({ foo, bar });
return {};
},
});
```
然后,在父组件中,可以使用 `ref` 获取子组件的实例,并调用子组件暴露的方法:
```typescript
import { defineComponent, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
setup() {
const childRef = ref(null);
const callChildMethod = () => {
childRef.value?.foo();
};
return { childRef, callChildMethod };
},
components: {
ChildComponent,
},
});
```
其中,`childRef` 是一个 `ref` 对象,用来保存子组件的实例。在模板中,需要将子组件的 `ref` 属性绑定到 `childRef` 上:
```html
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
```
这样就可以在父组件中调用子组件的方法了。