Prismic slices in Nuxtjs
How to use Prismic slices in Nuxtjs
Prismic
Prismic is a Headless CMS which is a cloud based service and allow non developers easily manage content of the websites and apps and for developers it is easy to build the UI with editable content. For more information about awesome Prismic features visit Prismic.io
Slices
Prismic slices are optional components such as paragraph, images etc. It is more like block in WordPress block editor, there are more chocolates inside, lol
By default the UI of your app may not render slice automatically. We are discussing a Nuxt project that render slices. Our Task is to render the slices in the index page
Dependecies
Install the necessary dependencies require for the working of slices.
npm i vue-slicezone npm i nuxt-sm
Vue-slice-zone
vue-sllicezone library will help us to render the necessary slices for us . For rendering we need a slice components. To specify the location of our Slices we need file called sm.json in the root with following content
//sm.json {"libraries": ["@/slices", "vue-essential-slices"]}
The vue-slicezone component will look for the slices folder for matching the snake_cased slices against PascalCased component . You can name the slices folder as you wish and must include in the libraries array of sm.json
Create Text Slice
Suppose you have a simple text_slice component in prismic. Create a TextSlice.vue with following code.
//slices/TextSlice.vue <template> <div> <prismic-rich-text :field="slice.primary.ritch_text_field" /> </div> </template> <script> export default { name:'TextSlice', props: { slice: Object, }, }; </script>
Add an index.js file to the slice folder
//slices/index.js import TextSlice from './TextSlice.vue' export { TextSlice, }
Lets render slices
Before beginning make sure that all slices in the current document (prismic.io) have PascalCased slices, otherwise it will end with an error.
What we need now ?
Document
A document that is already fetched using $prismic object which contain the slices object array, usually stored in a body object.
SliceZone component
The slice-zone component can be added using the import statement and can include in the template section as follows.
<template> .... <slice-zone class="subtitle" :slices="page.data.body" :resolver="resolver" /> </template> import SliceZone from "vue-slicezone"; ... components: { SliceZone, },
Since we are using Vue component , we need to setup component manually. The resolver method will instruct slice-zone which component to render. This also help us to specify only a few components to render by passing as an array.
In our case we have only one component, so need not go through the array option. Just import them all
..... import * as Slices from "@/slices"; .... methods: { resolver({ sliceName, slice, i }) { return Slices[sliceName]; }, },
And that's all. Have a question ? leave it in comment.
While I have the entire blogging platform done in Nuxt and Prismic and have a look @ GitHub
Comments