The first piece of functionality that you’ll implement in the app is loading and displaying a list of LinkItem
elements. You’ll walk your way up in the VueJS component hierarchy and start with the component that will render a single link.
This is a simple VueJS component that expects a link
in its props
and renders the link’s description
and url
. Easy as pie! 🍰
Next, you’ll implement the component that renders a list of links.
Here, you’re using mock data for now to make sure the component setup works. You’ll soon replace this with some actual data loaded from the server - patience, young Padawan!
Note that you only changed the template
and script
blocks here. You are now displaying the LinkList
component within the top-level App
component.
You need to make one more change before testing out the app.
Run the app to check if everything works so far (npm run dev
)! The app should now display the two links from the allLinks
array:
You’ll now load the actual links that are stored on the server. The first thing you need to do for that is define the GraphQL query that you want to send to the API.
Here is what it looks like:
query AllLinks {
allLinks {
id
createdAt
description
url
}
}
You could now simply execute this query in a Playground and retrieve the results from your GraphQL server. But how can you use it inside your JavaScript code?
When using VueJS with vue-apollo
the apollo
object makes it easy to fetch GraphQL data.
With this approach, all you need to do when it comes to data fetching is write the GraphQL query and apollo-client
will fetch the data for you under the hood and then make it available in your component’s data
.
In general, the process for you to add some data fetching logic will be very similar every time:
gql
parser functiondata
propertyapollo
object to fetch the results of your graphql
querydata
You will be writing your queries and mutations in a constants
folder and simply importing these queries and mutations into components as needed.
What’s going on here?
gql
from the graphql-tag
package. The gql
function is used to parse the plain GraphQL code.AllLinksQuery
is the operation name and will be used by Apollo to refer to this query in its internals. You export this parsed query as ALL_LINKS_QUERY
so you can easily import it into components.Next, you will add an apollo
object to the LinkList
component and call this newly created query to fetch data.
What’s going on here?
v-if
to display a loading indicator while data is being fetched.ALL_LINKS_QUERY
which you just createdallLinks
data property to an empty array, and loading
to 0. This will be incremented to 1 once data loads.apollo
object to your component and add an allLinks
property to it. This property requires a query
and you pass it the ALL_LINKS_QUERY
.That’s it! If you ran npm run dev
earlier, you should see your UI update and show the two links thanks to built-in hot-reloading.