Introduction to Template Directive v-html

Vue.js provides us with various directives for interpolation of the data in a various manner. Here we are discussing the data rendering as HTML. Vue.js provides us with the v-html  directive which helps us to render the raw HTML onto a div. This is very helpful in use cases where you want to give users an ability to render HTML data onto the screen from their user input. The typical use cases are as follows:-

  1. Commenting System
  2. Blogging Engines
  3. UI Editors
  4. Code Editors on the Web.

This particular article will deal with understanding this directive with a simple example where we build a simple code editor using a text area along with Twitter Bootstrap 3. Bootstrap will help with the layout for the editor. Let’s get started with the editor and see v-html directive in action.

Do remember that this directive may lead to Cross Site Scripting and you can solve it using Google Caja Along with Vue.js Computed Properties.

Implementation of the HTML Editor

This requires us to write a very simple interface using Bootstrap and HTML. The code for the markup is as shown below.

The above code will give rise to the image shown below.

Making Simple HTML Editor using v-html

Making Simple HTML Editor using v-html

Let’s write some Vue.js code to instantiate our application and do some data binding for the textarea. You might notice a few things in the HTML code though.

  1. We refer the app using the id app
  2. We are using Bootstrap to make these UI look and feel good
  3. Textarea is being bound using v-model  to a property text

The Vue.js code goes as shown below

This code is the fun part. When you have a look at the above code, you don’t find anything special apart from the data being bound to text property. This leads the Textarea’s data property to be Bi-directionally binded to the div which is rendering HTML using v-html. Now, this creates a magic. It renders Raw HTML into the Div and you can see it work like a charm. To see this in action have a look at the GIF and the JSFiddle.

HTML Editor with Some Sample HTML and Bootstrap+HTML

HTML Editor with Some Sample HTML and Bootstrap+HTML


This is how v-html directive brings in a lot of difference in which you represent data. It enables you using Raw HTML but be sure that it can cause XSS vulnerabilities that you might have to look into. In the next Article lets discuss out how will we prevent XSS vulnerabilities to hit us. It will be interesting to see it working.

Also published on Medium.

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!

Pin It on Pinterest

Share This