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.
What's inside vue-apollo
- 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.
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).Use the Vue Composition API for data and logic
The Composition API allows developers to write data and logic in a composable manner within thesetupoption 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>Access and use the $apollo manager in Vue components
The$apollomanager 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 viathis.$apollo.Execute GraphQL mutations using useMutation
TheuseMutationcomposable is used to define and trigger GraphQL mutation operations. It provides amutatefunction 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' } });Setup the Apollo Provider plugin in Vue v4
Instead of usingVue.use(VueApollo, { apolloClient }), v4 uses a provider pattern. Create a provider usingcreateApolloProviderand 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)Implement a lazy query using useLazyQuery
Use
useLazyQuerywhen you need to delay the execution of a query (e.g., waiting for a user action). It returns aloadfunction to initiate the request.load()returns a Promise of the result on the first call.load()returnsfalseon subsequent calls. To refresh data after the first load, use therefetch()function.
const { result, load, refetch } = useLazyQuery(gql` query list { list } `) async function handleLoad() { // load() returns false if already activated if (!load()) { refetch() } }Implement pagination using Apollo Vue's fetchMore
Use the
fetchMore()method on a Smart Query to load additional chunks of a large dataset. When implementingfetchMore, ensure you include the__typenamein the returned result to prevent data loss. Additionally, do not modify the initial variables returned byvariables()to avoid losing the existing list data.The
fetchMoremethod accepts avariablesobject for the next page request and anupdateQueryfunction 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>Configure JS GraphQL extension for Webstorm
To integrate GraphQL with Webstorm, install the JS GraphQL extension and create a.graphqlconfigJSON 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 } } } }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() })Execute a GraphQL mutation using useMutation
TheuseMutationcomposition function is the primary way to set up mutations in Vue components. It takes a GraphQL document as its first argument and returns amutatefunction which can be called to trigger the mutation. It is common practice to renamemutateto 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>Execute GraphQL queries using the ApolloQuery component
TheApolloQuery(orapollo-query) component allows you to execute watched Apollo queries directly in your Vue template. You can pass a function to thequeryprop that receives thegqltag as an argument to define the GraphQL document. The component provides a default slot that exposes aresultobject containingloading,error, anddatastates.<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>