父组件 ref 和子组件中 expose 类型声明

1.非 expose 抛出的组件方法

import { defineComponent, ref, onMounted } from '@vue/runtime-core'
import { ElForm } from 'element-plus'


export default defineComponent({

    setup() {
    
        const formRef = ref>(null)
        onMounted(() => {
            formRef.value?.validate((valid, failed) => {})
        })
        
        return () => 
            
    }

})
  1. expose 抛出的方法,我们需要自定义类型
import { defineComponent, ref, onMounted } from 'vue'
import { ElForm } from 'element-plus'

type ELEForm = InstanceType


// 在外界通过 ref 获取组件实例 请使用这个类型
export interface MyFormExpose {
  validate: ELEForm['validate'];
}

export const MyForm =  defineComponent({
    name: 'MyForm',

    setup(props, { expose }) {
    
        const formRef = ref>(null)
        
        expose({
          validate: (callback) => formRef.value?.validate(callback),
        } as MyFormExpose)
        
        return () => 
            
    }

})

父组件中使用

import {MyForm, MyFormExpose} from "./MyForm"
export const Parent = defineComponent({
  setup(props, context) {
    const formRef = ref & MyFormExpose>(null)
    onMounted(() => {
      formRef.value.validate()
    })
    return () => ()
  }
})

你可能感兴趣的:(父组件 ref 和子组件中 expose 类型声明)