vue3语法糖中父组件调用子组件中的方法如何有ts类型提示
时间: 2023-07-26 13:43:14 浏览: 53
在 Vue 3 的语法糖中,可以通过 `ref` 和 `$refs` 来实现父组件调用子组件中的方法并有 TypeScript 类型提示。
首先,在子组件中,使用 `defineExpose` 函数将要暴露给父组件的方法进行暴露。例如:
```typescript
import { defineComponent } from 'vue';
export default defineComponent({
setup() {
const myMethod = (data: string) => {
console.log(data);
};
defineExpose({
myMethod,
});
return {};
},
});
```
然后,在父组件中,通过 `ref` 获取子组件的实例,并使用 `$refs` 来获取子组件中暴露的方法。例如:
```typescript
import { defineComponent, ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
components: {
ChildComponent,
},
setup() {
const childRef = ref<InstanceType<typeof ChildComponent>>();
const handleChildMethod = () => {
if (childRef.value) {
childRef.value.$refs.childComponent.myMethod('data');
}
};
return {
childRef,
handleChildMethod,
};
},
});
```
注意,`$refs` 属性是一个对象,其中的属性名对应子组件中的 `ref`,属性值为子组件实例。因此,在调用子组件中的方法时,需要使用 `$refs` 对应的属性名,再使用方法名进行调用。
这样就可以实现父组件调用子组件中的方法并有 TypeScript 类型提示。