Integrate Contentful CMS in Vue 3, can be done using Graphql as well as the contentful library. We go with npm package.
Install the dependency by running the command yarn add contentful in terminal.
The client
We can a create client module in order to make contentful queries.
//contentdul/index.js
import {createClient} from 'contentful'
const client=createClient({
space:'w591jyzdi2py',
accessToken:'DXG7DohnxRncpcxSPtLGr5fR4_fzjyzRzVZAiP9Ussk'
});
export {client}
Replace the space and accessToken with your Contentful configurations which can be accessible in settings (contentful.com).
A list of posts
Using the getEntries async methos we can fetch the entries object. Since it is a an async call, we have to use a async component.
So lets create a list of posts
<template>
<div>
<h3> Contentful entries are ...</h3>
<ol v-for="post in posts.items">
<router-link :to="{path:`/post/${post.sys.id}`}">
<ul>{{ post.fields.title }}</ul>
</router-link>
</ol>
</div>
</template>
<script setup lang="ts">
import {client} from '@/contentful'
const posts = await client.getEntries();
</script>
<style scoped>
</style>
The above setup component is an async component since it has a top level await.
Render the list
In a View component , we can render the async component with optional fall back template.
<script setup lang="ts">
import PostList from '@/components/PostList.vue'
</script>
<template>
<div>
<h1>Posts</h1>
<suspense>
<post-list/>
<template #fallback>
loading ..
</template>
</suspense>
</div>
</template>
The same logic can be applied to a dynamic route. Please using dynamic route guide for Vue 3.
[display-post id=8704]