EthicsComputerCourses
Join training +91 90532 10052

HTML Integration with Vue.js

HTML · Lesson 191 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to predict the exact HTML a Vue template puts in the page, choose between v-if and v-show with accessibility in mind, keep lists, labels and component attributes correct, and avoid the browser-parser traps of in-DOM templates.

What you should know first: HTML in Templates & Frameworks (binding syntax, escaping, hydration), HTML Integration with React, HTML Error Recovery Mechanism and Accessible Form Error Handling. Vue itself is taught in the Vue.js tutorial; here we look only at the HTML it produces.

Versions: Vue 3.5.45 was the latest release on npm on 15 November 2026. The runnable examples load the course's pinned build, 3.5.44, from a CDN. The outputs shown were captured from that build in Chrome and from Vue's own compiler.

A template is HTML with a few extra attributes

A Vue template looks like HTML because it mostly is. Vue reads it, turns it into a render function (JavaScript that creates DOM nodes), and keeps the page in sync with your data. Think of a printed railway reservation form: the boxes are fixed HTML, and Vue is the clerk who fills in the blanks and updates them when your data changes.

Every Vue-only attribute disappears from the final HTML. Only real HTML is left. This table shows what Vue 3.5.44 really wrote into the DOM, with open set to false:

You writeWhat the DOM gets
<b>{{ name }}</b> with name = "<i>Isha</i>"<b>&lt;i&gt;Isha&lt;/i&gt;</b> (escaped text)
:aria-expanded="open"aria-expanded="false"
:disabled="false"no disabled attribute
:title="null"no title attribute
@click="save"nothing visible; a listener is attached
<p v-if="open"><!--v-if--> in development, <!----> in production
<p v-show="open"><p style="display: none;">
:key="item.id"nothing; keys stay inside Vue

Two rules come from this. First, null and undefined remove an attribute, and false removes boolean attributes such as disabled. Second, ARIA attributes keep the string "false", which is exactly what aria-expanded and aria-pressed need. You can bind them directly; see ARIA Roles & Attributes.

Escaping, v-html and URLs

{{ }} sets text, so a review that says <script> shows up as text. v-html sets innerHTML instead. Unlike Angular, Vue does not sanitise v-html at all: whatever string you pass becomes live HTML. Use it only for HTML you produced yourself, or pass it through a sanitiser such as DOMPurify first. HTML Injection & DOM-Based XSS explains the attacks.

Attribute bindings are escaped too, but escaping does not make a URL safe. :href="user.website" will happily output href="javascript:..." if a user typed that. Check that user-supplied URLs start with https: before binding them. The Accessibility & Security lesson in the Vue course has the full checklist.

Events do not add semantics

@click (short for v-on:click) attaches a listener and nothing else. It does not add a role, a tabindex or keyboard handling. So <div @click="addToCart"> renders as a plain <div>: a mouse can click it, but a keyboard user cannot reach it and a screen reader does not call it a button.

The fix is the same as in plain HTML: <button type="button" @click="addToCart">. For forms, listen on the form, not the button, so Enter still submits:

HTML
<form @submit.prevent="sendOtp">
  <label for="mobile">Mobile number</label>
  <input id="mobile" type="tel" autocomplete="tel" v-model="mobile" required>
  <button>Send OTP</button>
</form>

.prevent calls preventDefault() for you, so the page does not reload, while native validation such as required still runs first.

v-if or v-show

v-if removes the element from the DOM when false; Vue leaves a comment as a placeholder. v-show keeps the element and sets display: none. Both hide content from screen readers, so the difference is not "visible to some users". It is about whether the element exists.

That matters when other HTML points at it. A disclosure button with aria-controls="offers" refers to an element by id. With v-if, that element is gone while closed. Step 1: build both versions and print the DOM after each click.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>v-if vs v-show</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <div id="app">
    <h1>Shree Sweets, Jaipur</h1>
    <button type="button" aria-controls="hours" :aria-expanded="hoursOpen"
      @click="hoursOpen = !hoursOpen">Opening hours</button>
    <p id="hours" v-show="hoursOpen">Daily, 8 am to 10 pm</p>

    <button type="button" aria-controls="offers" :aria-expanded="offersOpen"
      @click="offersOpen = !offersOpen">Today's offers</button>
    <p id="offers" v-if="offersOpen">Ghewar at ₹450 per kg</p>
  </div>
  <pre id="out"></pre>

  <script>
    const { createApp, ref, watch, nextTick } = Vue;

    function report() {
      const lines = [];
      for (const button of document.querySelectorAll("#app button")) {
        const id = button.getAttribute("aria-controls");
        const target = document.getElementById(id);
        lines.push(button.textContent + ": aria-expanded=" + button.getAttribute("aria-expanded"));
        lines.push("  #" + id + " -> " + (target ? target.outerHTML : "MISSING from the DOM"));
      }
      document.querySelector("#out").textContent = lines.join("\n");
    }

    createApp({
      setup() {
        const hoursOpen = ref(false);
        const offersOpen = ref(false);
        watch([hoursOpen, offersOpen], () => nextTick(report));
        return { hoursOpen, offersOpen };
      },
      mounted() { report(); }
    }).mount("#app");
  </script>
</body>
</html>

At first, #hours exists with style="display: none;", while #offers is reported as missing, so its button's aria-controls points at nothing. Click both buttons and both panels exist. Use v-show for disclosures, tabs and menus that toggle often or are referenced by id. Use v-if for content that is rarely shown, expensive to build, or must not be in the DOM at all, such as an admin-only panel.

v-for on real lists

v-for repeats the element it sits on, so put it on the <li>, not on a wrapper <div> inside the <ul>. Always give :key a stable id, such as a station code, never the array index, so Vue moves the right DOM node (and its focus) when the list is re-ordered. See List Rendering.

For pairs of elements, such as the <dt> and <dd> of a description list, use <template v-for>. The <template> itself is not rendered:

HTML
<dl>
  <template v-for="train in trains" :key="train.no">
    <dt>{{ train.no }} {{ train.name }}</dt>
    <dd>Departs {{ train.time }}</dd>
  </template>
</dl>

Labels, ids and attribute fallthrough

v-model keeps an input and your data in sync, but it does not create a label. Each field still needs <label for> and a matching id. Inside a reusable component, a fixed id such as id="mobile" breaks as soon as the component appears twice on a page. Vue 3.5 added useId(), which returns an id that is unique in the app; in our build the first call returned v-0.

Components add one more rule, attribute fallthrough. Attributes you pass that are not props, such as class, aria-label, type or required, are copied onto the component's root element. In a field component the root is usually a wrapper <div>, which is the wrong place for required and autocomplete. Set inheritAttrs: false and bind $attrs to the input yourself.

Step 2: compare a field component with and without that fix.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Attribute fallthrough</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .field { margin-block: 8px; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <div id="app">
    <naive-field label="Mobile number" type="tel" autocomplete="tel" required></naive-field>
    <base-field label="Mobile number" hint="10 digits, without +91"
      type="tel" autocomplete="tel" required v-model="mobile"></base-field>
  </div>
  <pre id="out"></pre>

  <script>
    const { createApp, ref, useId } = Vue;

    const NaiveField = {
      props: ["label"],
      template: `<div class="field"><label>{{ label }}</label> <input></div>`
    };

    const BaseField = {
      inheritAttrs: false,
      props: ["label", "hint", "modelValue"],
      emits: ["update:modelValue"],
      setup() { return { id: useId() }; },
      template: `
        <div class="field">
          <label :for="id">{{ label }}</label>
          <input :id="id" v-bind="$attrs" :value="modelValue"
            :aria-describedby="hint ? id + '-hint' : null"
            @input="$emit('update:modelValue', $event.target.value)">
          <small v-if="hint" :id="id + '-hint'">{{ hint }}</small>
        </div>`
    };

    createApp({ setup() { return { mobile: ref("") }; } })
      .component("naive-field", NaiveField)
      .component("base-field", BaseField)
      .mount("#app");

    const fields = document.querySelectorAll("#app .field");
    document.querySelector("#out").textContent =
      "Naive:\n" + fields[0].outerHTML + "\n\nFixed:\n" + fields[1].outerHTML.replace(/\s+</g, "<");
  </script>
</body>
</html>

In the naive version, type, autocomplete and required land on the <div>, and the <label> is not connected, so the input has no accessible name and no validation. The fixed version puts every attribute on the <input>, links the label with for="v-0" and points aria-describedby at the hint.

If a component has several root elements, Vue cannot choose one, so it drops those attributes. The development build warns: Extraneous non-props attributes (class, aria-label) were passed to component but could not be automatically inherited because component renders fragment or text or teleport root nodes. More in Props.

In-DOM templates meet the HTML parser

When you mount Vue on markup that is already in the page, as in our runnable examples, the browser parses it first. Vue only sees what the parser left. Vue's documentation lists three consequences:

  • Names are case-insensitive, so write <fare-row> and :base-fare, not <FareRow> and :baseFare.
  • Only void elements may self-close. <fare-row /> is treated as an open tag that swallows what follows.
  • Elements with strict content models, such as <table>, <ul>, <ol> and <select>, throw unknown elements out. Write <tr is="vue:fare-row">; the vue: prefix tells Vue it means a component.

Step 3: see the third rule happen.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>In-DOM table caveat</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    table { border-collapse: collapse; margin-block: 8px; }
    td { border: 1px solid #999; padding: 4px 8px; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <div id="app">
    <table id="t1"><tbody><fare-row v-for="f in fares" :key="f.city" :fare="f"></fare-row></tbody></table>
    <table id="t2"><tbody><tr is="vue:fare-row" v-for="f in fares" :key="f.city" :fare="f"></tr></tbody></table>
  </div>
  <pre id="out"></pre>

  <script>
    const parsed = document.querySelector("#app").innerHTML;

    Vue.createApp({
      setup() {
        return { fares: [{ city: "Pune", rupees: 450 }, { city: "Kochi", rupees: 980 }] };
      }
    }).component("fare-row", {
      props: ["fare"],
      template: `<tr><td>{{ fare.city }}</td><td>₹{{ fare.rupees }}</td></tr>`
    }).mount("#app");

    document.querySelector("#out").textContent =
      "What the browser parsed before Vue started:\n" + parsed.trim() +
      "\n\nRows inside table 1: " + document.querySelectorAll("#t1 tr").length +
      "\nRows inside table 2: " + document.querySelectorAll("#t2 tr").length;
  </script>
</body>
</html>

The parsed markup shows <fare-row ...> sitting before the first <table>, which is left empty. After mounting, table 1 has 0 rows (they render outside it), and table 2 has 2.

Single-file components avoid the parser

In a real project you write single-file components (.vue files) and build them with Vite, as shown in Set Up Vue: CDN & Vite. Vue's own compiler reads these templates, so none of the in-DOM rules apply: PascalCase names and <FareRow /> work.

HTML
<!-- StopList.vue -->
<script setup>
const props = defineProps({ stops: Array })
</script>

<template>
  <ol class="stops">
    <li v-for="stop in props.stops" :key="stop.code">{{ stop.name }}</li>
  </ol>
</template>

<style scoped>
.stops li { padding: 4px; }
</style>

Compiled with Vue's compiler and rendered on the server with two stops, it produced:

Output
<ol class="stops" data-v-7f3c2a10><!--[--><li data-v-7f3c2a10>Pune Jn</li><li data-v-7f3c2a10>Lucknow</li><!--]--></ol>

scoped styles work by adding a data-v- attribute to every element and rewriting the CSS to .stops li[data-v-7f3c2a10]. Vite generates the id from the file; ours was set by hand. The <!--[--> and <!--]--> comments mark the list for hydration when you use server rendering, for example with Nuxt. The HTML is still a correct <ol> of <li> items.

Common mistakes

  • v-html on user content. Vue does not sanitise it.
  • @click on <div> or <span>. Use <button type="button"> or <a href>.
  • v-if on an element that aria-controls or a label points to.
  • v-for on a wrapper <div> inside a <ul>, or keys from the array index.
  • Fixed ids in reusable components. Use useId().
  • Self-closing or PascalCase component tags in in-DOM templates.

Interview questions

1. What is the difference between v-if and v-show?

v-if adds and removes the element, leaving a comment placeholder when false. v-show keeps it and toggles display: none. Both hide it from assistive technology; choose v-show for frequent toggles or when an id must stay available.

2. Is v-html safe if the string comes from your database?

Only if you control how it was created. Vue inserts it as raw HTML with no sanitising, so user-written content must go through a sanitiser such as DOMPurify first, or be shown with {{ }} instead.

3. What is attribute fallthrough, and when do you turn it off?

Non-prop attributes passed to a component, including class, style, ARIA attributes and listeners, are added to its root element. Turn it off with inheritAttrs: false when they belong on an inner element, such as the <input> inside a field wrapper, and bind $attrs there.

4. Why does a component inside <table> break in an in-DOM template but not in a .vue file?

In-DOM templates are parsed by the browser before Vue sees them, and the parser moves unknown elements out of tables. Use <tr is="vue:my-row">. Single-file components are parsed by Vue's compiler, so the restriction does not apply.

5. How do you give a reusable input component a unique id for its label?

Call useId() (added in Vue 3.5) in setup and use it for id, the label's for and any aria-describedby targets. It stays unique across the app and is stable between server and client renders.

Key points

  • Vue templates compile to plain HTML; directives, listeners and keys never reach the DOM.
  • {{ }} and bindings escape text; v-html inserts raw, unsanitised HTML.
  • null removes an attribute, false removes boolean attributes, and ARIA attributes keep "false".
  • v-if removes elements; v-show hides them with display: none.
  • Put v-for with a stable :key on the <li> itself, and use <template v-for> for pairs.
  • Use useId() for label ids and inheritAttrs: false with v-bind="$attrs" to place attributes on the right element.
  • In-DOM templates are parsed by the browser first: kebab-case, closing tags and is="vue:...".

Exercise

Build a runnable Vue page for Farhan's coaching centre in Lucknow. It lists three batches (name, days, seats left) in a <table> using a batch-row component written in the in-DOM template, plus a "Show fees" button that reveals a fee note with v-show, aria-expanded and aria-controls. Add an enquiry form built from a reusable field component that uses useId(), inheritAttrs: false and a hint linked with aria-describedby. Check the final DOM in DevTools: rows inside the table, attributes on the inputs, every input labelled.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Batches</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
</head>
<body>
  <div id="app">
    <h1>Batches in Lucknow</h1>
    <table>
      <thead><tr><th scope="col">Batch</th><th scope="col">Days</th><th scope="col">Seats left</th></tr></thead>
      <tbody>
        <tr is="vue:batch-row" v-for="b in batches" :key="b.name" :batch="b"></tr>
      </tbody>
    </table>
    <button type="button" aria-controls="fees" :aria-expanded="showFees" @click="showFees = !showFees">Show fees</button>
    <p id="fees" v-show="showFees">Fees start at ₹2,500 per month.</p>

    <form @submit.prevent="sent = true">
      <text-field label="Your name" autocomplete="name" required v-model="name"></text-field>
      <text-field label="Mobile number" hint="10 digits" type="tel" autocomplete="tel" required v-model="mobile"></text-field>
      <button>Send enquiry</button>
    </form>
    <p role="status">{{ sent ? "Thank you, " + name + "." : "" }}</p>
  </div>

  <script>
    const { createApp, ref, useId } = Vue;
    createApp({
      setup() {
        return {
          batches: [
            { name: "Morning", days: "Mon to Fri", seats: 4 },
            { name: "Evening", days: "Mon to Fri", seats: 9 },
            { name: "Weekend", days: "Sat, Sun", seats: 2 }
          ],
          showFees: ref(false), name: ref(""), mobile: ref(""), sent: ref(false)
        };
      }
    }).component("batch-row", {
      props: ["batch"],
      template: `<tr><th scope="row">{{ batch.name }}</th><td>{{ batch.days }}</td><td>{{ batch.seats }}</td></tr>`
    }).component("text-field", {
      inheritAttrs: false,
      props: ["label", "hint", "modelValue"],
      emits: ["update:modelValue"],
      setup() { return { id: useId() }; },
      template: `<p>
        <label :for="id">{{ label }}</label>
        <input :id="id" v-bind="$attrs" :value="modelValue"
          :aria-describedby="hint ? id + '-hint' : null"
          @input="$emit('update:modelValue', $event.target.value)">
        <small v-if="hint" :id="id + '-hint'">{{ hint }}</small>
      </p>`
    }).mount("#app");
  </script>
</body>
</html>

is="vue:batch-row" keeps the rows inside <tbody>, v-show keeps #fees in the DOM for aria-controls, and the field component puts type, autocomplete and required on the input with a unique, connected label. The status paragraph stays in the DOM, so screen readers announce the thank-you text when it changes.

Quick Quiz

1. What does :aria-expanded="false" render in Vue 3.5?

2. <p id="note" v-if="open"> is false. What is in the DOM?

3. Where do class and required go when passed to a component with one root <div>?

4. Which in-DOM template correctly renders a component row inside a table?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call