Vue Apollo Documentation

website·Indexed 19 days ago

https://v4.apollo.vuejs.org/

Documentation for vue-apollo 4, providing integration between Vue 3 and Apollo Client 3. Includes guides and API references for the composable API (@vue/apollo-composable), component-based approach (@vue/apollo-components), and option-based approach (@vue/apollo-option), covering queries, mutations, subscriptions, and SSR.

Tokens
26.7K
Snippets
133
Records
159
Agent score
96%

What's inside vue-apollo

  1. Overview of Vue Apollo integration

    The Vue Apollo library integrates Apollo Client into Vue components, allowing developers to use declarative queries to fetch and manage GraphQL data within their application.
  2. Overview of GraphQL Subscriptions

    GraphQL subscriptions allow a server to push real-time data to clients. Unlike queries, which return a single response, subscriptions send a result every time a specific event occurs on the server. They are ideal for scenarios where the initial state is large but incremental updates are small, or where low-latency updates are critical (e.g., chat applications).
  3. Use the Vue Composition API for data and logic

    The Composition API allows developers to write data and logic in a composable manner within the setup option of a Vue component. It is strongly recommended for projects using TypeScript due to its superior typing capabilities compared to other Vue APIs.
    <script>
    export default {
      props: ['userId'],
    
      setup (props) {
        // Add data and logic here...
    
        // Expose things to the template
        return {
          props.userId,
        }
      },
    }
    </script>
  4. Access and use the $apollo manager in Vue components

    The $apollo manager is automatically added to any Vue component that uses the Apollo integration. It provides a centralized interface to manage reactive queries, subscriptions, and direct Apollo client interactions. It is accessed within a component instance via this.$apollo.
  5. Execute GraphQL mutations using useMutation

    The useMutation composable is used to define and trigger GraphQL mutation operations. It provides a mutate function to execute the operation and reactive refs to track the mutation's state (loading, error, and whether it has been called).
    const { mutate, loading, error, called } = useMutation(MUTATION_DOCUMENT, options);
    
    // Trigger the mutation
    mutate({ variables: { id: '123' } });
  6. Setup the Apollo Provider plugin in Vue v4

    Instead of using Vue.use(VueApollo, { apolloClient }), v4 uses a provider pattern. Create a provider using createApolloProvider and install it into the Vue application instance.
    const httpLink = new HttpLink({
      uri: 'http://localhost:3020/graphql',
    })
    
    const apolloClient = new ApolloClient({
      link: httpLink,
      cache: new InMemoryCache(),
      connectToDevTools: true,
    })
    
    const apolloProvider = createApolloProvider({
      defaultClient: apolloClient,
    })
    
    const app = createApp(/* ... */)
    app.use(apolloProvider)
  7. Implement a lazy query using useLazyQuery

    Use useLazyQuery when you need to delay the execution of a query (e.g., waiting for a user action). It returns a load function to initiate the request.

    • load() returns a Promise of the result on the first call.
    • load() returns false on subsequent calls. To refresh data after the first load, use the refetch() function.
    const { result, load, refetch } = useLazyQuery(gql`
      query list { list }
    `)
    
    async function handleLoad() {
      // load() returns false if already activated
      if (!load()) {
        refetch()
      }
    }
    
  8. Implement pagination using Apollo Vue's fetchMore

    Use the fetchMore() method on a Smart Query to load additional chunks of a large dataset. When implementing fetchMore, ensure you include the __typename in the returned result to prevent data loss. Additionally, do not modify the initial variables returned by variables() to avoid losing the existing list data.

    The fetchMore method accepts a variables object for the next page request and an updateQuery function to merge the new results (fetchMoreResult) with the existing data (previousResult).

    <template>
      <div id="app">
        <h2>Pagination</h2>
        <div class="tag-list" v-if="tagsPage">
          <div class="tag-list-item" v-for="tag in tagsPage.tags">
            {{ tag.id }} - {{ tag.label }} - {{ tag.type }}
          </div>
          <div class="actions">
            <button v-if="showMoreEnabled" @click="showMore">Show more</button>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    import gql from 'graphql-tag'
    
    const pageSize = 10
    
    export default {
      name: 'app',
      data: () => ({
        page: 0,
        showMoreEnabled: true,
      }),
      apollo: {
        tagsPage: {
          query: gql`query tagsPage ($page: Int!, $pageSize: Int!) {
            tagsPage (page: $page, size: $pageSize) {
              tags {
                id
                label
                type
              }
              hasMore
            }
          }`,
          variables: {
            page: 0,
            pageSize,
          },
        },
      },
      methods: {
        showMore () {
          this.page++
          this.$apollo.queries.tagsPage.fetchMore({
            variables: {
              page: this.page,
              pageSize,
            },
            updateQuery: (previousResult, { fetchMoreResult }) => {
              const newTags = fetchMoreResult.tagsPage.tags
              const hasMore = fetchMoreResult.tagsPage.hasMore
    
              this.showMoreEnabled = hasMore
    
              return {
                tagsPage: {
                  __typename: previousResult.tagsPage.__typename,
                  tags: [...previousResult.tagsPage.tags, ...newTags],
                  hasMore,
                },
              }
            },
          })
        },
      },
    }
    </script>
  9. Configure JS GraphQL extension for Webstorm

    To integrate GraphQL with Webstorm, install the JS GraphQL extension and create a .graphqlconfig JSON file in the project root to define the schema path and API endpoints.
    {
      "name": "Untitled GraphQL Schema",
      "schemaPath": "./path/to/schema.graphql",
      "extensions": {
        "endpoints": {
          "Default GraphQL Endpoint": {
            "url": "http://url/to/the/graphql/api",
            "headers": {
              "user-agent": "JS GraphQL"
            },
            "introspect": false
          }
        }
      }
    }
  10. Perform simple unit tests for vue-apollo queries

    For simple query testing in vue-apollo, you can manually set the component's data to a mocked array of results and verify the rendered output using Jest snapshots. This approach avoids the need for a full Apollo client setup during the test.
    test('displayed heroes correctly with query data', () => {
      const wrapper = shallowMount(App, { localVue })
      wrapper.setData({
        allHeroes: [
          {
            id: 'some-id',
            name: 'Evan You',
            image: 'https://pbs.twimg.com/profile_images/888432310504370176/mhoGA4uj_400x400.jpg',
            twitter: 'youyuxi',
            github: 'yyx990803',
          },
        ],
      })
      expect(wrapper.element).toMatchSnapshot()
    })
  11. Execute a GraphQL mutation using useMutation

    The useMutation composition function is the primary way to set up mutations in Vue components. It takes a GraphQL document as its first argument and returns a mutate function which can be called to trigger the mutation. It is common practice to rename mutate to a more descriptive name (e.g., sendMessage) for better readability.
    <script>
    import { useMutation } from '@vue/apollo-composable'
    import gql from 'graphql-tag'
    
    export default {
      setup () {
        const { mutate: sendMessage } = useMutation(gql`
          mutation sendMessage ($text: String!) {
            sendMessage (text: $text) {
              id
            }
          }
        `)
    
        return {
          sendMessage,
        }
      },
    }
    </script>
    
    <template>
      <button @click="sendMessage({ text: 'Hello' })">
        Send message
      </button>
    </template>
  12. Execute GraphQL queries using the ApolloQuery component

    The ApolloQuery (or apollo-query) component allows you to execute watched Apollo queries directly in your Vue template. You can pass a function to the query prop that receives the gql tag as an argument to define the GraphQL document. The component provides a default slot that exposes a result object containing loading, error, and data states.
    <template>
      <ApolloQuery
        :query="gql => gql`
          query MyHelloQuery ($name: String!) {
            hello (name: $name)
          }
        `"
        :variables="{ name: 'Anne' }"
      >
        <template v-slot="{ result: { loading, error, data } }">
          <div v-if="loading">Loading...</div>
          <div v-else-if="error">An error occurred</div>
          <div v-else-if="data">{{ data.hello }}</div>
          <div v-else>No result :(</div>
        </template>
      </ApolloQuery>
    </template>