First create a new Vue.js application using Vue CLI. During the creation wizard, go ahead and pick the default preset (babel, eslint).
If you want to use Nuxt.js then just use its scaffolding tool create-nuxt-app.
npm install -g @vue/clivue create my-appVue CLI? Please pick a preset: (Use arrow keys)❯ default (babel, eslint)Manually select features
Enter inside the my-app
directory, and install the graphql-request
package:
cd my-appnpm install --save graphql-request
First we need to setup our GraphQL client pointing to one of our GraphQL Content Delivery API endpoints, so inside the src
folder create a file called datocms.js
:
import { GraphQLClient } from "graphql-request";export function request({ query, variables, preview }) {const endpoint = preview? `https://graphql.datocms.com/preview`: `https://graphql.datocms.com/`;const client = new GraphQLClient(endpoint, {headers: {authorization: `Bearer ${process.env.VUE_APP_CMS_DATOCMS_API_TOKEN}`}});return client.request(query, variables);}
On line 10 we're using an environment variable starting with VUE_APP_
, so that it will be statically embedded into the client bundle. If you're using Nuxt, then you need to prefix the environment variable with NUXT_ENV_
.
To create the API token for a DatoCMS project, go in the "Settings > API Tokens" section, making sure you only give it permissions to access the (read-only) Content Delivery API.
Now we can set the env variable inside a file called .env.local
(which by default is ignored by git), and start the development server:
echo 'VUE_APP_CMS_DATOCMS_API_TOKEN=YOUR-API-TOKEN' > .env.localnpm run serve
The setup is done, and we can now start fetching data from DatoCMS and use it inside our Vue.js application.
Next, go to src/App.vue
and use the request
function we just created on src/datocms.js
to perform your first GrapQL query:
<template><div><div v-if="loading">Loading...</div><div v-else-if="error">Something bad happened</div><div v-else>{{data}}</div></div></template><script>import { request } from "./datocms";const HOMEPAGE_QUERY = `query HomePage($limit: IntType) {allBlogPosts(first: $limit) {title}}`;export default {name: "App",data: () => ({data: null,error: null,loading: true,}),async mounted() {try {this.data = await request({query: HOMEPAGE_QUERY,variables: {limit: 10}});} catch (e) {this.error = e;}this.loading = false;}};</script>
The HOMEPAGE_QUERY
is the GraphQL query, and of course it depends on the models available in your specific DatoCMS project.
You can learn everything you need regarding how to build GraphQL queries on our Content Delivery API documentation.