How to Implement Previews with Nuxt Applications using a Strapi backend

  1. Introduction
  2. Enabling preview mode in Nuxt (> v2.13)
  3. Previewing brand new pages
  4. Generating Posts in Strapi
  5. Conclusion

Prerequisites

  1. Basic knowledge of JavaScript
  2. Basic knowledge of Vue.js
  3. Basic knowledge of Nuxt.js
  4. Basic understanding of Strapi — get started here.

Enabling preview mode in Nuxt (> v2.13)

npx create-nuxt-app nuxt-preview-demo
// plugins/preview.client.js
export default function ({ query, enablePreview }) {
if (query.preview) {
enablePreview()
}
}
export default {
//...
plugins: ['~/plugins/preview.client.js'] //...
}
npx nuxt generatenpx nuxt start

Previewing brand new pages

validate({ params, query }) {
if (query.preview) {
return true
}

What is Strapi?

Scaffolding a Strapi App

yarn create strapi-app nuxt-preview-api --quickstartcd nuxt-preview-api// If the server is not started by default
yarn develop

Build the collection

Integrating Strapi with Nuxt Preview

Creating Pages

touch posts/index.vue
<template>
<div>
<section>
<div class="container">
<h3 class="mt-5 text-center">Top Rated Posts</h3>
<p>A list of our highly rated posts.</p>
<Posts class="text-left" />
</div>
</section>
</div>
</template>
<script>
export default {}
</script>
// /components/Posts.vue<template>
<div class="row row-cols-1 row-cols-md-3 g-4">
<Post v-for="post in posts" :key="post.id" :post="post" />
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
posts: (state) => {
return state.posts
},
}),
},
}
</script>
<style></style>
<template>
<div class="col">
<div class="card h-100">
<div class="card-body">
<h5 class="card-title">{{ post.Title }}</h5>
<p class="card-text">
{{ post.description }}
</p>
<nuxt-link :to="`/posts/${post.id}`" class="btn btn-primary text-white"
>View Post</nuxt-link
>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
post: {
type: Object,
default: () => {},
},
},
}
</script>
<style scoped>
a {
color: inherit;
}
</style>
// store/index.js
export const state = () => ({
posts: [],
})
export const mutations = {
STORE_POSTS(state, posts) {
state.posts = posts
},
}
export const actions = {
async nuxtServerInit({ commit }) {
const posts = await this.$axios
.$get('http://localhost:1337/posts')
.catch((e) => console.error(e))
commit('STORE_POSTS', posts)
},
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Strapi

Strapi

2.1K Followers

The open source Headless CMS Front-End Developers love.