Binding with HTML in VueJS

Learn how to bind texts with HTML in VueJS?
Submitted by Venkatesan C, on March 09, 2022

Prerequisite: VueJS – Template Syntax

  • Binding texts to a template tag is done using mustache syntax and v-text directive.
  • What if you have bound an HTML element to a template tag? It is completely possible in VueJS.

However one might have a question: why is there a need to bind an Html element dynamically?

The answer is, suppose you have to develop a rich text editor, in this case, you have to have options to make text italic, bold, make text bigger etc.

These are possible with the help of, dynamically binding HTML to the templates dynamically.

Let's look at an example by creating a Vue project created by Vite. Let's name it second-app (in fact this is the same project that's been created in the VueJS installation tutorial).

Here's the project structure:

Binding with HTML | Output 1

Now delete everything inside the App.vue file and paste the below code. The below is simpler to understand the binding HTML concept.

App.vue

<template>
  {{htmlCode}}
 
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      htmlCode: "<h1>This is a heading tag</h1>"
    };
  },
};
</script>

The above tries to bind the Html with the mustache syntax. But it won't work.

Output:

Binding with HTML | Output 2

The reason why it doesn't work is that the mustache syntax can only interpret the property's value as string alone, even if the value is an Html element. Hence, we have to use a different method to bind the Html element. Here comes the v-html directive.

You can even see the DOM structure by inspecting the elements in the elements tab. You can view this by the following shortcut Ctrl + Shift + I.

Binding with HTML | Output 3

As you can see, the htmlCode property didn't get interpreted as an Html element, rather as a text.

Now replace everything inside the template tag with the below line.

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

Now look at the output. It gets interpreted as an Html element, as it is highlighted as a heading tag.

Binding with HTML | Output 4

Look at the inspect elements tab as well.

Binding with HTML | Output 5

Hence, for binding an Html, v-html directive should be used not the mustache syntax.

Important note:

  • Whenever you are binding an Html element, always make sure you bind only the elements that you are confident it is safe to bind.
  • Bind only the elements that you know and you are in control with.
  • Never bind elements that are derived from the user's input without proper sanitization checks and validation.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.