1.非 expose 抛出的组件方法
import { defineComponent, ref, onMounted } from '@vue/runtime-core'
import { ElForm } from 'element-plus'
export default defineComponent({
setup() {
const formRef = ref<InstanceType<typeof ElForm>>(null)
onMounted(() => {
formRef.value?.validate((valid, failed) => {})
})
return () =>
<ElForm ref={formRef}></ElForm>
}
})
- expose 抛出的方法,我们需要自定义类型
import { defineComponent, ref, onMounted } from 'vue'
import { ElForm } from 'element-plus'
type ELEForm = InstanceType<typeof ElForm>
// 在外界通过 ref 获取组件实例 请使用这个类型
export interface MyFormExpose {
validate: ELEForm['validate'];
}
export const MyForm = defineComponent({
name: 'MyForm',
setup(props, { expose }) {
const formRef = ref<InstanceType<typeof ElForm>>(null)
expose({
validate: (callback) => formRef.value?.validate(callback),
} as MyFormExpose)
return () =>
<ElForm ref={formRef}></ElForm>
}
})
父组件中使用
import {MyForm, MyFormExpose} from "./MyForm"
export const Parent = defineComponent({
setup(props, context) {
const formRef = ref<InstanceType<typeof MyForm> & MyFormExpose>(null)
onMounted(() => {
formRef.value.validate()
})
return () => (<MyForm ref={formRef}/>)
}
})