How to render an HTML String with custom Vue Components

Render Custom Components from a HTML-String

You want to use a Headless CMS, but you don’t want to loose your custom Vue.JS Components. What can you do?

What is actually the Problem? Why not use v-html?

I thought that as well! But it turns out, that v-html can only render plain html. Your custom components are not getting resolved. So if you get some string like "<div><FancyButton>Button</FancyButton></div>” from your API and use <div v-html="myString"/> , FancyButton will not be rendered. Actually it will be rendered as FancyButton, but your browser will not understand it and handle it like a plain old div element.

no fancy button, just some boring text 😪

Any other Ideas? Yes!

I found this great article from Kengo Hamasaki / hmsk. He does something pretty similar but with a markdown source. So I can just skip some steps (converting markdown to html) and write a render function that fullfills my needs.

What Kengo Hamasaki / hmsk does is pretty smart. He uses the Vue compiler to compile the html string and then pass this compiled output to the render function. That’s it.

Extending the base implementation

This component would already work, but it could only render components that are mounted in the Vue Instance. You could now import all the Components you need, and register them under components .

But there is a better way. You can extend the implementation.

You just need to import the RenderHtml component we just created and mount all the components we want to use in our new component.

The FancyButton —

Et voila: The ExtendedRenderHtml.vue can now understand and show FancyButton .

I hope you have learned something new today.🤗 And if you have any other ideas, how to solve this problem, please let me know in the comments. Im also eager to learn something new every day!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Day 29 Training at Ryaz: Starting Javascript

React Hooks

Your trial feed URL has expired on Sun Jan 16, 2022

SpringBoot project logging with Lombok

Javascript : Dot (.) notation vs Bracket [] notation

Building an Angular Library with the Angular CLI (version 6)

Node vs Angular.js: A Detailed Comparison

How do I learn GreenSock?

new animation

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
Adrian Jost

Adrian Jost

More from Medium

ESlint Shareable configs for Vue

Persistent Vuex Store For Only Specific Modules

Reusable Widgets that work! — Vue Amsterdam Conference 2022 Summary series — Fifth Talk

Vue Recaptcha