DEV Community

Cover image for Rendering HTML code in Vue
mattiatoselli
mattiatoselli

Posted on

Rendering HTML code in Vue

Let us suppose that we want to pass to the page as an attribute, a variable containing html code.
Like a clickable link. Following the previous tutorials one could think this is the right way.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        <a href="{{ link }}">This is the link</a>
    </div>
    <script type="text/javascript">
        var app = new Vue({
          el: '#app', 
          data: {
            link: 'https://www.google.com' //this is the link
          }
        })
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Actually this will lead to an error. Vue is unable to link the value of the attribute. In order to accomplish the task, we have to use the bind directive.

<a v-bind:href="link">This is the link</a>
Enter fullscreen mode Exit fullscreen mode

For some reason, we may want to render html code instead of just saving the link in the data key of the vue instance and injecting it in the anchor tag, Vue provides the "v-html" directive.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- importing vue js dev library -->
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <title>My vue Test</title>
</head>
<body>
    <div id="app">
        <p v-html="link"></p>
    </div>
    <script type="text/javascript">
        var app = new Vue({
          el: '#app', 
          data: {
            link: '<a href="https://www.google.com">This is the link</a>' //this is the link
          }
        })
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Discussion (0)