DEV Community

Cover image for Rendering HTML code in Vue
mattiatoselli
mattiatoselli

Posted on

7 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay