How to render an HTML String with custom Vue Components

Adrian Jost
2 min readNov 25, 2019

--

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 — https://codepen.io/ZachSaucier/pen/WyJqdL

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!

--

--