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>
// 在外界通過(guò) ref 獲取組件實(shí)例 請(qǐng)使用這個(gè)類型
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}/>)
}
})