Use graphql to make queries from the backend.
- Backend should be set up with content added to it.
- Use Apollo to write graphql queries
- Nuxt should be set up and able to access the backend
- create a directory called
apollo/queries/- inside this directory make your query files. ie:
articles.gql
- inside this directory make your query files. ie:
- add query to the file
query Articles {
articles {
id
name
}
}
- Import the query from the
gqlfile - Put this in the script tag above the export
import articlesQuery from '~/apollo/queries/article/articles'
- Set up
apolloin the export part of the script
apollo: {
articles: {
prefetch: true,
query: articlesQuery
}
}
- Add the uri to the
data()function
data() {
return {
api_url: process.env.strapiUrl
}
}
- Create a article component
components/Articles.vue- import articles into the component
- Add queried content into the article
- Create a page to add the article component to
pages/index.vue- import the articlesQuery and Articles component
- Add the component to the page
<Articles :articles="articles">- This will send the articles to the page
- Create a folder with a slug file
pages/articles/_id.vue
- this layout is used to show the article content
- import the query
- import moment
- the data() function should return an article object, moment, and the api_url env
- Also include apollo in the export. include
query Articles($id: ID!) {
article(id: $id) {
id
title
content
image {
url
}
published_at
}
}
- install markdownit with the package
@nuxtjs/markdownit - add it to the nuxt.config.js file and add settings
modules: [ '@nuxtjs/apollo', '@nuxtjs/markdownit' ], markdownit: { preset: 'default', linkify: true, breaks: true, injected: true }
<div v-if="article.content" id="editor" v-html="$md.render(article.content)></div>
- this means if there is an article content to render the content.
- call the Articles component to show all of the articles in the category
<Articles :articles="category.articles || [] />
- This will bind the category.articles or an empty array to the articles component which will use that information to populate itself
- To make your graphql call for individual categories to post them onto pages, you will need to use
$id. ex:
query Category($id: ID!) {
category(id: $id) {
name
articles {
id
title
content
image {
url
}
category {
id
name
}
}
}
}
- This will call the category being selected, and then show it's name as well as all the articles and categories attached to it