乐趣区

关于vue3:vue3-ts-获取组件-ref-实例

在 vue3 中获取组件的类型:

type EleForm = InstanceType<typeof ElForm>

在 template 中获取组件的 ref

<template>
  <ElForm ref="$form"></ElForm>
</template>

<script lang="ts">
import {Options, Vue} from 'vue-class-component'
import {ElForm} from 'element-plus'

@Options<Home>({
  components: {ElForm,},

})
export default class Home extends Vue {$form = ref<InstanceType<typeof ElForm>>(null)
  
  mounted() {this.$form?.value // 类型正确}
}
</script>

tsx 等 render 组件中获取的形式更简略

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


export default defineComponent({setup() {const $form = ref<InstanceType<typeof ElForm>>(null)
        
        onMounted(() => {$form?.value // 类型正确})
        
        return () => 
            <ElForm ref={$form}></ElForm>
    }

})

须要留神的是,如果应用 expose 裸露办法进来,无奈获取到对应的类型,您须要自定义类型
https://github.com/vuejs/rfcs…

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

type ELEForm = InstanceType<typeof ElForm>


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

export default defineComponent({
    name: 'MyForm',

    setup(props, { expose}) {const $form = ref<InstanceType<typeof ElForm>>(null)
        
        expose({validate: (callback) => $form?.value?.validate(callback),
        } as MyFormExpose)
        
        return () => 
            <ElForm ref={$form}></ElForm>
    }

})
<!-- Home.vue -->
<template>
  <MyForm :ref="$form" />
</template>

<script>
import {defineComponent, ref, onMounted} from '@vue/runtime-core'
import MyForm, {MyFormExpose} from '@/components/MyForm'
export default defineComponent({components: { MyForm}
  
  setup(){const $form = ref<InstanceType<typeof MyForm> & MyFormExpose>(null)
    
    onMounted(() => {$form?.value.validate // 类型正确})
  }
})
</script>
退出移动版