Working with Rich Text and Vue

In this post we’ll explore using GraphCMS Rich Text with Vue.

Jamie Barton
Jamie Barton
vue and rich text

To follow along with this post you'll need: * A Vue project already running, and connected to GraphCMS, * A model with a Rich Text field, and some content published.

If you’re new to Vue and GraphCMS, this video should show how to get started:

Start by installing the @graphcms/rich-text-html-renderer dependency within your project.

npm install –save-exact @graphcms/rich-text-html-renderer

Then inside of any Vue route where you're fetching the model data that has a Rich Text field you will want to get the AST, and any embedded references. Your query may look something like:

query GetPosts {
pages {
content {
json
references {
... on Post {
id
title
}
... on Asset {
url
width
height
}
}
}
}
}

If you'd prefer to follow along with some sample data, you can find that here.

The @graphcms/rich-text-html-renderer exports the method astToHtmlString that we’ll need to import. Don't forget to also import ref from vue as we'll need that too:

<script lang="ts" setup>
import { ref } from 'vue';
import { astToHtmlString } from '@graphcms/rich-text-html-renderer';
</script>

We'll now take the Rich Text AST (json + references) and convert it to HTML, providing the references, and custom renderers using astToHtmlString:

<script lang="ts" setup>
import { ref } from 'vue';
import { astToHtmlString } from '@graphcms/rich-text-html-renderer';
// const content = 'your query response for json/content'
// const references = 'your query response for references'
const html = astToHtmlString({
content,
references,
renderers: {
bold: props => `<strong>${props.children}</strong>`,
Asset: {
application: () => `<div><p>Asset</p></div>`,
text: () => `<div><p>text plain</p></div>`,
},
},
});
const richTextHtml = ref(html);
</script>

You'll see above we can pass custom renderers to astToHtmlString.

This means you can override the default HTML element for what's to be shown in the Rich Text. This is extremely useful for things like links in Nuxt that you might want to default to providing extra attributes to an href such as nuxt-link.

Now all that’s left to do is invoke the built-in directive v-html to render our html. If you’ve used libraries like React, you can think of this similar to dangerouslySetInnerHTML. Learn more about the v-html directive over on the Vue docs.

<div v-html="richTextHtml"></div>

That’s it! You will now see the Rich Text output with any custom renderers applied.

It's Easy To Get Started

GraphCMS plans are flexibly suited to accommodate your growth. Get started for free, or request a demo to discuss larger projects with more complex needs