Article image

HOW TO DISPLAY UNESCAPED HTML IN VUE.JS

Javascript -

Oct 11 2019

Dino Numic

Often times we have a rich text editor on our web application that let's the user insert formatted HTML code and store it in the database as such. This can be seen on blogs, such as this one, web shops for products descriptions, and etc.

We can quickly run into issues if we were to just print out the raw HTML code as our Vue application would try to execute it. This is especially an issue if you want to display raw Vue code like bellow.

This would be stored as a content of our article in the database.

<template>
        <table class="table table-hover">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">Email</th>
                    <th scope="col">Updated At</th>
                    <th scope="col">Created At</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(user, index) in users" :key="user.id">
                    <td>{{ index + 1 }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.updated_at }}</td>
                    <td>{{ user.created_at }}</td>
                </tr>
            </tbody>
        </table>
</template>
<script>
    export default {
        data() {
            return {
                users: []
            }
        },
        created() {
            axios.get('/api/users')
                .then(response => {
                    this.users = response.data.data;
                })
                .catch(error => {
                    console.log("Error", error)
                })
        }
    }
</script>

This is how we would call it.

<div id="body-wrap">
    {!! $article->content !!}
</div>

Vue would raise multiple errors over this, from undefined properties and methods, to component registration. In order to solve this issue, we can use v-pre directive. This will tell Vue to skip compilation on this element and elements inside it and just print out the raw content.

<div id="body-wrap" v-pre>
    {!! $article->content !!}
</div>

Awesome, isn't it.