LoginSignup
11

More than 3 years have passed since last update.

Nuxt(compositionAPI)にvue-apollo v4(@vue-composable)を導入する

Last updated at Posted at 2019-12-21

この記事は Nuxt.js Advent Calendar 2019 22日目の記事です。

Nuxt(Composition API×TypeScript)でvue-apollo(v4)のvue-composableを使いたい!(長い) となったので記します。

構成

  • Nuxt
  • Composition API
  • Typecript

why vue-apollo?

nuxtでapolloを扱うときには通常、apollo-moduleを使用するかと思います。
Nuxtでvue-apolloを使うため、vue-apolloをラップしたライブラリです。

しかし、今回はvue-apolloの新しい機能 @vue/apollo-composable を使いたい。Composition API用に作られていてイイ感じに動いてくれます。
Nuxt用にラップしたライブラリが見つからないので直接使用します。

どうすればNuxtに組み込めるか迷ったので、記します

手順

1: Composition APIのバージョンを0.3.3以上にする
2: 必要なパッケージをインストールする

yarn add @nuxtjs/apollo graphql-tag @vue/apollo-composable apollo-boost apollo-client

3: apollo-module用の設定

nuxt.config.js
  modules: [
      '@nuxtjs/apollo'
    ],
  apollo: {
      clientConfigs: {
        default: {
          httpEndpoint: '' // endpointのURL
        }
      },
      includeNodeModules: true
  },

4: ルートに注入する

src/plugins/provide-apollo-client.js
import { provide } from '@vue/composition-api'
import { DefaultApolloClient } from '@vue/apollo-composable'
import ApolloClient from 'apollo-boost'

const apolloClient = new ApolloClient({
  uri: '' //endpointのURL
})
export default function({ app }) {
  app.setup = () => {
    provide(DefaultApolloClient, apolloClient)
  }
}

5: プラグインの登録

nuxt.config.js
 plugins: ['@/plugins/provide-apollo-client'],

6: 型を定義

src/shims-gql.d.ts
declare module '*.gql' {
  import Graphql from 'graphql'
  export default Graphql
}

7: 定義した型を適用

tsconfig.json
  "files": [
    "shims-vue.d.ts",
    "shims-gql.d.ts"
  ],
  "include": [
    "apollo/queries/*.gql",
    "apollo/queries/**/*.gql"
  ],

ここまでで、設定は完了して、疎通できる状態になりました

使い方

ドキュメント を見て。

Result にはref(?)がかけられてて、イイ感じに使えます。
使いたいものをピックアップとかしたかったら、useResultを使おう。

参考

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
11