vue3 ts 獲取組件 ref 實例


原文地址:https://segmentfault.com/a/1190000040098033

在 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暴露方法出去,無法獲取到對應的類型,您需要自定義類型
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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 vue3 + ts(typescript) ref 獲取單個/多個dom元素 Vue使用Ref跨層級獲取組件實例 vue3