How to convert string to HTML in VueJS?

Hi Friends 👋,

Welcome To SortoutCode! ❤️

To convert string to HTML in vueJS, we are using the v-html to convert string to HTML, we are passing the string with some string HTML tag And returning the output with HTML.

Today I am going to show you How do you convert string to HTML in VueJS.

Table of contains

  • Define msg property for Test
  • Define computed property libText

Let’s start today’s tutorial How do I convert string to HTML in VueJS?

Define msg property for Test

Let’s define the msg in the data of the FirstComponent.vue component for testing purposes.

FirstComponent.vue

<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            msg: "Hi Friends Welcome To SortoutCode",
        }
    },
}
</script>

Data is used to define properties in a particular component. In a single-file component, data() is a function that returns a set of properties that have been defined in the function.

we define the three properties that are msg.

Define computed property libText

In vueJS, computed properties enable you to create the property that can be used to modify, manipulate or display data in components in a readable and efficient manner.

In this case, we are using for to concatenate the html tag and string.

you can see the code:

FirstComponent.vue

<template>
    <div v-html="libText">{{libText}}</div>
</template>
<script>
export default {
    name: 'FirstComponent',
    data(){
        return{
            msg: "Hi Friends Welcome To SortoutCode",    
        }
    },
    computed: {           
        libText:function(){
            // return directly html
            var str="<p><b>" + this.msg + "<b></p>";
            return str;
        }
    },
}
</script>

we are using the v-html to show the string as you see them in the code.

For now, let’s check the output.

Output

String to Html

All the best 👍.

Follow me on Twitter