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.

Blog site end result

Info

Prerequisites

You need to have the following setup before you connect your Vue project to Prepr.

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.

  1. 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.

vue settings

  1. 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
  1. You should now be able to view your app on your localhost, for example, http://localhost:3000/.

  2. Open your Vue project with your preferred code editor.

  3. Go to the src/views folder and replace the contents of the HomeView.vue file with the following code to display a single heading:

<!-- ./src/views/HomeView.vue -->

<template>
  <div>
    <h1>My blog site</h1>
  </div>
</template>
  1. Replace the code in the App.vue file in the src folder with the code below to remove the Vue welcome and formatting from the page.
<!-- ./src/App.vue -->

<script setup>
import { RouterView } from 'vue-router'
</script>

<template>
  <RouterView />
</template>
  1. This example doesn't include any styling, so go to the src/assets folder and empty the main.css file to remove the existing styling.

You should now see something like the image below on your localhost.

view component

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 so that you can execute GraphQL queries to request data from the Prepr API.

  1. 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
  1. Create a folder called services in the src folder. Then, create a file called apollo-client.js in this folder. Copy the following code to this file to import the Apollo client:
// ./src/services/apollo-client.js 

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;
  1. Add the code below to the main.js in the src 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')
  1. 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:
# ./.env

VITE_PREPR_ACCESS_TOKEN=<YOUR-ACCESS-TOKEN>
  1. 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.

access token list

Note

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.

  1. 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

  1. Go to the src folder and create a queries directory. In here, create a file named get-articles.js.

  2. Add the following query to this file to retrieve all articles:

// ./src/queries/get-articles.js

import gql from 'graphql-tag'

export const GetArticles = gql`
  query {
    Articles {
    items {
      _id
      _slug
      title
    }
  }
 }
`

Tip

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.

demo articles

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.

  1. Open the HomeView.vue file and add a script and HTML to execute the query and display the query results with the code below.
<!-- ./src/views/HomeView.vue -->

<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.

articles on site

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.

  1. Update the HomeView.vue file to include a router-link tag on each article title as shown in the code below.
<!-- ./src/views/HomeView.vue -->


<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.

  1. We added the Vue router as part of the installation, so adding routing is simple. Just update the index.js file in the router folder to add a route to the detailed article page as follows:
// ./src/router/index.js

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.

  1. Create a file called get-article-by-slug.js in the queries folder and add the following query to this file to query a specific article by its slug:
// ./src/queries/get-article-by-slug.js

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.

Note

  1. Open the views folder and create a new file ArticleView.vue with the following code:
<!-- ./src/views/ArticleView.vue -->

<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.

Article end result

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: