In this tutorial, we will learn how to convert a Vue string to HTML, with or without v-html
. In the first example, we will use v-html
to render the string as HTML, and in the second example, we will not use v-html
; instead, we will do it with the simple JavaScript innerHTML
method.
How can you convert a string into HTML using Vue.js?
In this code, we demonstrate how to convert a string to HTML using v-html
. If you want to edit or customize the given code, use the TryIt editor and make it according to your preference
Vue Js Convert String into HTML Example
<div id="app">
<!-- Render HTML from a data property -->
<div v-html="htmlString"></div>
<!-- Render HTML from a method -->
<div v-html="getHtmlString()"></div>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
htmlString: '<p> This is some <strong> HTML </strong> content. </p>'
};
},
methods: {
getHtmlString() {
return ' <p> This is some <strong> HTML </strong> content from a method. </p>';
}
}
})
</script>
Output of Vue Js Convert String into HTML
Example 2 : Vue Render HTML without v-html
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {};
},
mounted() {
const htmlString = `
<h1>This is Heading</h1>
<p>This is Paragraph</p>`;
this.$refs.htmlContainer.innerHTML = htmlString;
}
})
</script>