在 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 {
// 请注意,从 `setup` 返回的 refs 在模板中访问时会自动展开,因此模板中不需要 `.value`
// https://v3.cn.vuejs.org/api/options-composition.html#setup
// 所以需要转换 ref 的返回值为 any,修正 $form 的类型
$form: InstanceType<typeof ElForm> | null = ref<any>(null)
mounted() {
this.$form?.validate // 类型正确
}
}
</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?.validate // 类型正确
})
return () =>
<ElForm ref={$form}></ElForm>
}
})
需要注意的是,如果使用expose暴露方法出去,无法获取到对应的类型,您需要自定义类型
// 组件 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>
网友评论