Use Apollo in your VueJS app

Declaratively attach GraphQL queries to your components

Guillaume CHAU
Apollo GraphQL
2 min readSep 27, 2016

--

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:

Create Apollo client and install Vue plugin

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’:

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

Vue component example

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:

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:

Update your data with GraphQL mutations

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

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.

--

--