Vue Quick start guide
Estimated duration: 10 minutes
This guide shows you how to connect Prepr to a Vue project to get data from Prepr CMS. You'll learn how to make a simple blog with Vue and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.
If you want to skip ahead, try out the zero installation demo on Stackblitz (opens in a new tab) or clone the repository on GitHub (opens in a new tab) to run the demo locally.
Prerequisites
You need to have the following setup before you connect your Vue project to Prepr.
- A free Prepr account (opens in a new tab)
- An environment with demo data in Prepr
- The latest version of Node.js (opens in a new tab)
Step 1: Create a new Vue project
The instructions below will guide you on how to create an empty Vue project for your blog app.
If you have an existing Vue project then you can skip this step.
- Open a terminal and execute the command below to create a new Vue project called
prepr-vue
.
npm init vue@latest prepr-vue
Mark the options as shown in the image below to create the same project structure used in this guide.
- When the project is successfully created, go to the
prepr-vue
folder, the root directory of the project, and execute the commands below in the terminal to start the project.
cd prepr-vue
npm install
npm run dev
-
You should now be able to view your app on your localhost, for example,
http://localhost:3000/
. -
Open your Vue project with your preferred code editor.
-
Go to the
src/views
folder and replace the contents of theHomeView.vue
file with the following code to display a single heading:
<template>
<div>
<h1>My blog site</h1>
</div>
</template>
- Replace the code in the
App.vue
file in thesrc
folder with the code below to remove the Vue welcome and formatting from the page.
<script setup>
import { RouterView } from 'vue-router'
</script>
<template>
<RouterView />
</template>
- This example doesn't include any styling, so go to the
src/assets
folder and empty themain.css
file to remove the existing styling.
You should now see something like the image below on your localhost.
Step 2: Install the Apollo client
The Apollo client is an integration tool that helps to retrieve CMS data with GraphQL. The instructions below show you how to install the Apollo client (opens in a new tab) so that you can execute GraphQL queries to request data from the Prepr API.
- Stop the server you started in the above step (
CTRL-C
) and run the commands below in the terminal to install the Apollo client to execute GraphQL queries in a Vue project.
npm install --save graphql graphql-tag @apollo/client
npm install --save @vue/apollo-option @apollo/client
- Create a folder called
services
in thesrc
folder. Then, create a file calledapollo-client.js
in this folder. Copy the following code to this file to import the Apollo client:
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
// HTTP connection to the API
const httpLink = createHttpLink({
// You should use an absolute URL here
uri: `https://graphql.prepr.io/${import.meta.env.VITE_PREPR_ACCESS_TOKEN}`,
})
// Cache implementation
const cache = new InMemoryCache()
// Create the apollo client
const apolloClient = new ApolloClient({
link: httpLink,
cache,
})
export default apolloClient;
- Add the code below to the
main.js
in thesrc
folder to import and create the Apollo Provider.
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// Import the Apollo provider and the apollo client
import {createApolloProvider} from "@vue/apollo-option";
import apolloClient from "@/services/apollo-client";
// Initiate the Apollo provide
const apolloProvider = createApolloProvider({
defaultClient: apolloClient,
})
const app = createApp(App)
app.use(router)
//Include the Apollo Provider in the app
app.use(apolloProvider)
app.mount('#app')
- We recommend using environment variables to store sensitive information like access tokens. To add environment variables, create a
.env
file in the root directory of your project and add the access token like this:
VITE_PREPR_ACCESS_TOKEN=<YOUR-ACCESS-TOKEN>
- Replace the placeholder value
<YOUR-ACCESS-TOKEN>
with an access token from Prepr. Get an access token by logging into your Prepr account:
a. Go to Settings → Access tokens to view all the access tokens.
b. Copy the GraphQL Production access token to only retrieve published content items on your site.
Use the GraphQL Production access token to request published content items for your live app and use the GraphQL Preview token to make a preview of unpublished content items for your content editors.
- Execute the following command to make sure that the Apollo client is installed correctly:
npm run dev
If your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the installed Apollo client.
Step 3: Fetch multiple articles
Now that your Apollo client is installed and connected to Prepr, fetch the blog articles from Prepr.
Add a GraphQL query
-
Go to the
src
folder and create aqueries
directory. In here, create a file namedget-articles.js
. -
Add the following query to this file to retrieve all articles:
import gql from 'graphql-tag'
export const GetArticles = gql`
query {
Articles {
items {
_id
_slug
title
}
}
}
`
You can create and test GraphQL queries using the Apollo explorer (opens in a new tab) from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.
If you’re using preloaded demo data in your Prepr CMS environment as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.
In the next step, we'll fetch and process the query response.
Fetch data
Now that the query has been added, fetch the articles from Prepr and display them in the app.
- Open the
HomeView.vue
file and add a script and HTML to execute the query and display the query results with the code below.
<script>
import {GetArticles} from "@/queries/get-articles";
export default {
apollo: {
Articles: GetArticles
},
data() {
return {
Articles: ''
}
},
}
</script>
<template>
<div>
<h1>My blog site</h1>
<!-- Loop through articles and display the article title -->
<ul v-if="Articles">
<li v-for="article in Articles.items" :key="article._id">
{{article.title}}
</li>
</ul>
</div>
</template>
Now when you view the website on your localhost, you'll see something like the image below.
Step 4: Fetch individual articles
Now that you have the list of articles, add links to them. When a visitor clicks on a link, your app should open a detailed article page automatically. The instructions below show you how to create a route from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.
Create dynamic routing
First add links to the articles.
- Update the
HomeView.vue
file to include arouter-link
tag on each article title as shown in the code below.
<script>
import {GetArticles} from "@/queries/get-articles";
export default {
apollo: {
Articles: GetArticles
},
data() {
return {
Articles: ''
}
},
}
</script>
<template>
<div>
<h1>My blog site</h1>
<ul v-if="Articles">
<li v-for="article in Articles.items" :key="article._id">
<!-- Add link to the slug on each article title -->
<router-link :to="article._slug">{{article.title}}</router-link>
</li>
</ul>
</div>
</template>
Now when you view the app, each article has its own link. When you click on the link, a new page opens with the slug in the URL, but the article details are not yet visible. Let's add the route to the detailed article page.
- We added the Vue router as part of the installation, so adding routing is simple. Just update the
index.js
file in therouter
folder to add a route to the detailed article page as follows:
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
//Import the detailed article page
import ArticleView from "@/views/ArticleView.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'home',
component: HomeView
},
// Include routing to the detailed article page with the slug from the URL
{
path: '/:slug',
name: 'article',
component: ArticleView
}
]
})
export default router
Continue with the next step to fetch the article details and display the page.
Fetch article details
Add another query to fetch a specific article by its slug and make this page visible when clicking on an article.
- Create a file called
get-article-by-slug.js
in thequeries
folder and add the following query to this file to query a specific article by its slug:
import gql from 'graphql-tag'
export const GetArticleBySlug = gql`
query ($slug: String) {
Article (slug: $slug) {
_id
title
content {
__typename
... on Text {
body
text
}
... on Assets {
items {
url
}
}
}
}
}`
Now that the query is added, fetch the individual article by its slug. Fetch the article title and the article content.
The Article content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.
- Open the
views
folder and create a new fileArticleView.vue
with the following code:
<script>
import {GetArticleBySlug} from "@/queries/get-article-by-slug";
export default {
data() {
return {
Article: null,
}
},
apollo: {
Article: {
query: GetArticleBySlug,
variables () {
return {
slug: this.$route.params.slug
}
}
}
},
}
</script>
<template>
<h1>{{Article.title}}</h1>
<div :key="contentType._id" v-for="contentType in Article.content">
<!-- Display images if they exist -->
<div v-if="contentType.__typename === 'Assets'" class="my-10">
<img
v-if="contentType.items.length"
:src="contentType.items[0]?.url"
:alt="`Image for ${Article.title}`"
width="300"
height="250"
/>
</div>
<!--Display the text in HTML format -->
<div
v-if="contentType.__typename === 'Text'"
v-html="contentType.body"
></div>
</div>
</template>
Now, when you view your site, you can click on an article which will direct you to that specific article like in the image below.
All done
Congratulations! You have successfully connected a Vue project to Prepr for a simple Blog app.
Next steps
To learn more on how to expand your project, check out the following resources:
Was this article helpful?
We’d love to learn from your feedback