えぐろぐ

https://twitter.com/eggpogg

Nuxt x TypeScript の $refs で Vueコンポーネントの関数の呼び方

// components/Hoge.vue

<template>
  <div></div>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  name: 'Hoge',
  methods: {
    moge(): string {
      return 'moge'
    },
  },
})
</script>
// page/index.vue

<template>
  <div>
    <Hoge ref="hoge" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Hoge from '~/components/Hoge.vue'

export default Vue.extend({
  mounted() {
    const hoge = this.$refs.hoge as InstanceType<typeof Hoge>
    console.log(hoge.moge())
  },
})
</script>

$refsの実装は以下のようになっていた

VueEelementが返ってくる。 HogeコンポーネントはVueクラスの拡張クラスなので、返り値の抽象化されたVueから辿れるようになっている 👀

readonly $refs: { [key: string]: Vue | Element | Vue[] | Element[] }

InstanceTypeの実装は以下になっている

名前と説明の通りで、Constructor関数で作成されるインスタンスの型のTypeを取得する 🚀

/**
 * Obtain the return type of a constructor function type
 */
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;

www.typescriptlang.org