Template Syntax and New Features

Explore the changes and new features in Vue 3 template syntax and learn the essentials of component development.

🎯 Introduction

Vue 3 introduces changes and improvements to template syntax, including multiple root nodes, updated v-model bindings, slot syntax, directive precedence, fallthrough attributes, event modifiers, and the new Teleport and Suspense components. Understanding these features helps you write concise, efficient applications and explore Vue 3's design and more advanced usage.


🌿 Multiple Root Nodes & Fragments

In Vue 2, a component template must have exactly one root node, a common limitation. Vue 3 removes this restriction: you can write multiple sibling elements without adding a wrapper.

<template>
    <header>This is the header</header>
    <main>This is the main content</main>
    <footer>This is the footer</footer>
</template>

Multiple root nodes are implemented using fragments in the virtual DOM. Vue 3 groups the roots into a fragment without creating an extra DOM element, keeping the structure clean.

This makes component structure more flexible, removes unnecessary wrappers, and simplifies styling and layout.

When using multiple root nodes, pay attention to fallthrough attributes. Vue cannot automatically determine which DOM node should receive attributes passed by the parent that are not declared as props.

🔄 Updated v-model Syntax

Standard v-model Usage

Receive the value through modelValue and emit changes through update:modelValue. You can add formatting or validation logic in the getter and setter.

<template>
    <input v-model="model" />
</template>

<script setup>
import { computed } from 'vue';
const props = defineProps({
    modelValue: String,
});

const emit = defineEmits(['update:modelValue']);

const model = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    },
});
</script>

The defineModel Shorthand

This concise syntax removes the need to declare props, emit, and computed manually. It requires Vue 3.4 or later.

<template>
    <input v-model="model" />
</template>

<script setup>
const model = defineModel();
</script>

Multiple v-model Bindings

Vue 3 supports multiple v-model bindings targeting different props, for example:

<ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />

ChildComponent needs to declare the corresponding props and events:

<script setup>
const title = defineModel('title');
const content = defineModel('content');
</script>

🎭 Slot Syntax Changes (Named and Scoped Slots)

Slot syntax is largely familiar in Vue 3, but <template #name> replaces the older Vue 2 slot="name" syntax. Scoped slots also use the concise v-slot shorthand.

Named Slots

Traditional Vue 2 syntax:

<template>
    <ChildComponent>
        <template slot="header">This is the header</template>
    </ChildComponent>
</template>

Recommended Vue 3 syntax:

<template>
    <ChildComponent>
        <template #header>This is the header</template>
    </ChildComponent>
</template>

Scoped Slots

Vue 3 also offers concise syntax for scoped slots:

<template>
    <ChildComponent>
        <template #default="{ user }">
            <p>Username: {{ user.name }}</p>
        </template>
    </ChildComponent>
</template>
# is shorthand for v-slot, making slot declarations concise, consistent, and easy to read.

⚖️ Changes to v-if and v-for Precedence

Vue 3 changes the precedence of v-if and v-for: v-if now has higher priority. This changes how the directives interact in more complex rendering scenarios.

A Problematic Vue 2 Pattern

<li v-for="item in list" v-if="item.visible">{{ item.name }}</li>

Although this works in Vue 2, v-if is evaluated inside the v-for loop.

Vue 3 Example to Review

<template v-for="item in list" v-if="item.visible">
    <li>{{ item.name }}</li>
</template>
Avoid using v-if and v-for on the same element. In the example above, v-if is evaluated before item is in scope, so the example still has this problem. Put v-for on the outer template and v-if on the inner li instead.

🧩 Fallthrough Attributes

Vue 3 components support fallthrough attributes by default. Attributes passed by a parent that are not declared by the component are automatically applied to its root element.

ParentCompoennt.vue
<ChildComponent id="foo" class="bar" />

If ChildComponent does not declare id and class, both attributes still fall through to its root element.

ChildComponent.vue
<template>
    <div>
        <!-- id and class are automatically applied here -->
    </div>
</template>

Disabling Automatic Attribute Inheritance

If you do not want attributes applied automatically, use inheritAttrs: false.

<script setup>
defineOptions({ inheritAttrs: false });
</script>

Then apply them to a specific element manually with v-bind="$attrs".

Fallthrough attributes reduce boilerplate and make components more flexible. Use them carefully so that attribute placement remains predictable.

🔔 Event Modifier Features

Vue 3 supports event modifiers such as .once, .passive, and .capture. These provide convenient control over event handling.

<button @click.once="handleClick">Click once</button>
<button @scroll.passive="handleScroll">Listen for scrolling</button>
<button @click.capture="handleCapture">Capture-phase event</button>
  • .once: run the handler only once; subsequent events do not invoke it.
  • .passive: tell the browser the handler will not call preventDefault, improving performance, especially for scrolling interactions.
  • .capture: run the handler during the capture phase rather than the bubbling phase.
Using event modifiers appropriately can improve page performance and make event handling more precise.

🚀 Using Teleport and Suspense

Teleport

Teleport is a new Vue 3 component that renders its child content at a specified location in the DOM tree. It is commonly used for modals and overlays.

<template>
    <Teleport to="body">
        <div class="modal">This is the modal content</div>
    </Teleport>
</template>

<style>
.modal {
    position: fixed;
    top: 30%;
    left: 50%;
    transform: translate(-50%, -30%);
    background: white;
    padding: 20px;
    border: 1px solid #ccc;
}
</style>
Teleport lets a component's DOM content escape its parent's hierarchy, giving you more control over modal and overlay positioning.

Suspense

Suspense waits for asynchronous components or data dependencies to resolve before displaying their content, improving the loading experience.

<template>
    <Suspense>
        <template #default>
            <AsyncComponent />
        </template>
        <template #fallback>
            <div>Loading...</div>
        </template>
    </Suspense>
</template>

<script setup>
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'));
</script>

Here, Suspense first displays the fallback content, then displays the default slot once the asynchronous component has loaded.

Suspense helps manage loading states more cleanly in asynchronous workflows.

🎨 Dynamic CSS Values with v-bind

Vue 3 lets you use v-bind inside a component's <style> block to reference reactive variables. Their values are injected into the styles automatically, keeping presentation in sync with state using concise syntax.

<template>
    <button @click="toggleColor">Toggle button color</button>
</template>

<script setup>
import { ref } from 'vue';

const isRed = ref(true);

function toggleColor() {
    isRed.value = !isRed.value;
}
</script>

<style scoped>
button {
    background-color: v-bind(isRed ? 'red': 'blue');
    color: white;
    border: none;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 16px;
    border-radius: 4px;
    transition: background-color 0.3s;
}
</style>
Use v-bind in a component's <style> block, including <style scoped>, rather than in a standalone global stylesheet.

❓ Questions and Answers

Q1: Why does Vue 3 support multiple root nodes?

Vue 3 introduces fragments, allowing the virtual DOM to handle multiple root nodes without requiring a single root element. This makes component structure more flexible.

Q2: Which prop and event does v-model use in Vue 3?

The event is update:modelValue, and the prop is modelValue.

Q3: What are practical uses for Teleport?

Typical uses include modals, overlays, and notifications that need to render outside their parent's DOM hierarchy.


🧪 Exercises

Exercise 1

Create a Vue 3 component with multiple root nodes for a header, main content, and footer. Use a fragment without adding a wrapper element.

<template>
    <!-- Add your code here -->
</template>

Exercise 2

Build a custom input component with two v-model bindings for title and content.


🎉 You now understand multiple root nodes, updated v-model bindings, slot syntax, directive precedence, fallthrough attributes, event modifiers, and how to use Teleport and Suspense in Vue 3! Keep practicing as you develop your frontend skills.