Skip to content
文章目录

给自定义vue组件标注ts类型

我们需要为一个子组件添加一个模板 ref,以便调用它公开的方法。比如,我们有一个 MyModal 子组件,它有一个打开模态框的方法:

html
<!-- MyModal.vue -->
<script setup lang="ts">
  import { ref } from 'vue'

  const isContentShown = ref(false)
  const open = () => (isContentShown.value = true)

  defineExpose({
    open,
  })
</script>

为了获取 MyModal 的类型,我们首先需要通过 typeof 得到其类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型:

html
<!-- App.vue -->
<script setup lang="ts">
  import MyModal from './MyModal.vue'

  const modal = ref<InstanceType<typeof MyModal> | null>(null)

  const openModal = () => {
    modal.value?.open()
  }
</script>

参考资料

如何为 Vue3 组件标注 TS 类型,看这个就够了!