LoginSignup
21
12

More than 3 years have passed since last update.

[TypeScript] Nuxt.jsでプロジェクト共通で使う関数や変数を定義する場合はInjectを使う(サンプルコードつき)

Last updated at Posted at 2020-05-21

筆者のバージョン

nuxt: 2.11.0

産業

  • pluginsに適切な形でInjectを書いてnuxt.config.tsで参照する
  • types/vue.d.tsにグローバル定義するものの型定義を書く
  • context.app.$someMethods に入るので、asyncDataなりtemplateなりstoreなりで参照する(勝手にダラーがつくので気にしなくていい)

pluginsにInject構文を記述する

第一引数のcontextは使わないのだが、ないとエラーが出てしまうので必要
引数が必要なメソッドの場合でもおk

some.ts
import { Plugin } from '@nuxt/types'
import { useGlobalMethods } from '~/utils/nantoka.ts'

const plugin: Plugin = (context, inject) =>
  inject('getAuthority', useGlobalMethods)

export default plugin

型定義を書く

正しく型定義する

types/vue.d.ts
import { APIClient } from './api'
import { GraphQLClient } from './graphql'
import { UseGlobalMethods } from '~/commons/interfaces/useGlobalMethods'

// vue.prototypeに入るやつっぽい
declare module 'vue/types/vue' {
  interface Vue {
    $api: APIClient
    $gql: GraphQLClient
    $useGlobalMethods: (
      argument1: string,
      argument2: number
    ) => boolean
  }
}

// contextに入るやつっぽい
declare module '@nuxt/types' {
  interface NuxtAppOptions {
    $api: APIClient
    $gql: GraphQLClient
  }
  interface Context {
    $api: APIClient
  }
}

// vuexに入るやつっぽい
declare module 'vuex/types/index' {
  interface Store<S> {
    $api: APIClient
  }
}

画面から呼ぶ

適当

contextのドット記法がだるいときはこれでもいける

async asyncData({ app: { $useGlobalMethods } }) {

pages/index.vue
<template>
 <p>{{ $constantsWords.SERVICE_NAME }}</p>
</template>


// いろいろ省略
<script lang="ts">
  async asyncData(context) {
    const isActive = context.app.$useGlobalMethods('aaa', 2)

    return {
      isButtonActive: isActive
    }
  }
</script>

参考リンク

TypeScript のサポート — Vue.js

21
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
12