September 27, 2016

Use Apollo in your VueJS app

Guillaume Chau

Guillaume Chau

Editor’s note: This post is from Guillaume Chau, an Apollo contributor who built an integration package between VueJS and Apollo. Check it out and contribute to it here!

As you may know, the Apollo team has built a great GraphQL client and tooling that makes it easy to use data from your server in any JavaScript app. Why not use it with another amazing technology like VueJS?

Now you can do just that with vue-apollo, an npm package I wrote that allows you to write GraphQL queries in your VueJS components while using Apollo under the hood.

Use it in your VueJS app

First, install these packages in your project folder:

npm install — save apollo-client vue-apollo

Then, you need to create an Apollo client and install the vue-apollo plugin into VueJS:

1import Vue from 'vue';2import App from './App.vue';3import ApolloClient, { createNetworkInterface, addTypename } from 'apollo-client';4import VueApollo from 'vue-apollo';56// Create the apollo client7const apolloClient = new ApolloClient({8  networkInterface: createNetworkInterface({9    uri: 'http://localhost:8080/graphql',10    transportBatching: true,11  }),12  queryTransformer: addTypename,13  dataIdFromObject: r => r.id,14});1516// Install the vue plugin17// With the apollo client instance18Vue.use(VueApollo, {19  apolloClient,20});2122// Start the Vue app23new Vue({24  el: '#app',25  render: h => h(App)26});

Fetch data with GraphQL queries

You can now use Apollo directly in your components to query your GraphQL server. Inside a component, the Apollo client can be accessed with ‘this.$apollo’:

1<script>2export default {3  created() {4    this.$apollo.watchQuery({5      /* options */6    }).then(data => {7      console.log(data);8    });9  },10};11</script>

But the preferred way to make queries is to declare them with the ‘apollo’ option in the component definition:

1<script>2import gql from 'graphql-tag';3// GraphQL query4const postsQuery = gql`5  query allPosts {6    posts {7      id8      title9      votes10      author {11        id12        firstName13        lastName14      }15    }16  }17`;18// Vue component definition19export default {20  // Local state21  data: () => ({22    // You can initialize the 'posts' data here23    posts: [],24    loading: 0,25  }),26  // Apollo GraphQL27  apollo: {28    // Local state 'posts' data will be updated29    // by the GraphQL query result30    posts: {31      // GraphQL query32      query: postsQuery,33      // Will update the 'loading' attribute34      // +1 when a new query is loading35      // -1 when a query is completed36      loadingKey: 'loading',37    },38  },39};40</script>4142<template>43  <div class="post-list">44    <!-- If there is one or more queries loading -->45    <template v-if="loading > 0">46      Loading47    </template>48    <!-- Actual view -->49    <template v-else>50      <ul>51        <!-- Post list items -->52        <li v-for="post in posts" :key="post.id">53          {{ post.title }} by54          {{ post.author.firstName }} {{ post.author.lastName }}55        </li>56      </ul>57    </template>58  </div>59</template>

Thanks to the VueJS reactivity system, the ‘posts’ local data will be automatically updated with the GraphQL query result and your DOM updated.

You can initialize the corresponding data attribute in the ‘data’ hook with a default value:

12  // Local state3  data: () => ({4    // You can initialize the 'posts' data here5    posts: [],6    loading: 0,7  }),

If you want to update your data automatically when another user changes it, you can poll the server with the ‘pollInterval’ option, specifying an interval duration in milliseconds:

12  apollo: {3    posts: {4      query: postsQuery,5      loadingKey: 'loading',6      // Polling query7      pollInterval: 300, // ms8    },9  },

Update your data with GraphQL mutations

In the component methods and hooks, you can use the ‘$apollo’ object to call mutations:

1<script>2import gql from 'graphql-tag';3// GraphQL Mutation with one parameter4const upvoteMutation = gql`5  mutation upvotePost($postId: Int!) {6    upvotePost(postId: $postId) {7      id8      votes9    }10  }11`;12export default {13  // Attribute14  props: {15    // Post id passed down to this component16    postId: {17      type: Number,18      required: true,19    },20  },21  methods: {22    upvote() {23      // Mutation24      this.$apollo.mutate({25        mutation: upvoteMutation,26        variables: {27          postId: this.postId,28        },29      }).then(data => {30        console.log('Done upvoting.');31      });32    },33  },34};35</script>3637<template>38  <button @click="upvote">Upvote</button>39</template>

In this component, we call the ‘upvotePost’ mutation on the GraphQL server, that returns the updated post data. That way, the Apollo cache is up-to-date, and again, thanks to VueJS reactivity system, your view should reflect the new votes count.


These are just the basics of using Apollo in your VueJS components. The more advanced features in vue-apollo are documented here, and you can take a look at the hello world example to have a better idea of how things work.

Written by

Guillaume Chau

Guillaume Chau

Read more by Guillaume Chau