Vue3 Template Tag<template>
In Vue3,<template>the <template> tag is a very core concept.
<template>It is used to define the template structure of a component, and is the foundation for Vue to render pages.
<template>Basic Concept of the Tag
<template>The <template> tag is a tag in Vue3 used to define a component template. It is not rendered into the final DOM itself, but serves as a container to wrap Vue's template syntax (such as interpolation, directives, etc.). Vue will, based on the<template>content within it, generate the actual HTML structure.
Features
- Non-rendered tag:
<template>The tag itself will not appear in the final DOM structure. - Template container: It is used to wrap Vue's template syntax, such as interpolation, conditional rendering, list rendering, etc.
- Supports multiple root nodes: In Vue3,
<template>the <template> tag can contain multiple root nodes, whereas in Vue2 it can only have one.
<template>Usage Scenarios of the Tag
1. Defining a Component Template
In a single-file component (.vuefile),<template>the <template> tag is used to define the template part of a component. For example:
Example
<div>
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
</template>
<script>
export default {
data() {
return {
title: "Hello Vue3",
description: "This is a Vue3 template example."
};
}
};
</script>
2. Conditional Rendering
<template>The tag can be used withv-iforv-elsedirectives to implement conditional rendering. For example:
Example
<div>
<template v-if="isVisible">
<p>This content is visible.</p>
</template>
<template v-else>
<p>This content is hidden.</p>
</template>
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
};
}
};
</script>
3. List Rendering
<template>The tag can be used withv-fordirectives to implement list rendering. For example:
Example
<ul>
<template v-for="item in items" :key="item.id">
<li>{{ item.name }}</li>
</template>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Orange" }
]
};
}
};
</script>
<template>Notes on the Tag
- Does not support dynamic attributes:
<template>The tag itself does not support dynamic attributes (such as:classor:styleetc.), because it will be ignored during rendering. - Avoid nested usage: Although
<template>the tag can be nested, excessive nesting may reduce code readability. - and
v-slotUse with: In Vue3,<template>the tag is commonly used to define slot content, for example:
Example
<MyComponent>
<template v-slot:header>
<h1>Header Content</h1>
</template>
<template v-slot:default>
<p>Default Content</p>
</template>
</MyComponent>
</template>
Other extensions
Vue3 Options API