Vue <template> 元素


示例

使用内置的<template>元素来切换 HTML 代码的一部分v-if指示。

<ul>
  <li>Trolltunga</li>
  <template v-if="display">
    <li>Potato Point</li>
    <li>The souks of Marrakech</li>
    <li>Dry Tortugas</li>
    <li>Halong Bay</li>
  </template>
  <li>...</li>
</ul>
运行示例 »

定义和用法

HTML<template>tag 成为 Vue 内置<template>与 Vue 指令一起使用时的元素v-if,v-else-if,v-else,v-for, 或者v-slot

当与v-if,v-else-if,v-else, 或者v-for,内置的<template>元素呈现一段 HTML 代码。

当与v-slot,内置的<template>元素将一段 HTML 代码定向到指定的槽。请参见下面的示例 1。

内置的<template>元素本身不呈现为 DOM 元素。

笔记:顶层<template>元素是使用 SFC (*.vue) 文件时的结构要求。对于这样的顶级<template>元素,不能使用 Vue 指令。


更多示例

示例1

使用内置的<template>元素封装多个元素并将它们发送到特定的命名槽v-slot指示。

<template>
  <h1>App.vue</h1>
  <p>The component has two div tags with one slot in each.</p>
  <slot-comp>
    <template v-slot:bottomSlot>
      <h4>To the bottom slot!</h4>
      <p>This p tag and the h4 tag above are directed to the bottom slot with the v-slot directive used on the template tag.</p>
    </template>
    <p>This goes into the default slot</p>
  </slot-comp>
</template>
运行示例 »

示例2

使用<template>元素,可以使用以下方式渲染多个元素v-if指示。

<div id="app">
  <template v-if="text.includes('pizza')">
    <p>The text includes the word 'pizza'</p>
    <img src="img_pizza.svg">
  </template>
  <p v-else>The word 'pizza' is not found in the text</p>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
  const app = Vue.createApp({
    data() {
      return {
        text: 'I like taco, pizza, Thai beef salad, pho soup and tagine.'
      }
    }
  })
  app.mount('#app')
</script>
亲自试一试 »

相关页面

Vue教程:Vue v 槽

Vue教程:Vue 模板

Vue教程:Vue v-if 指令

Vue参考:Vue v-if 指令

Vue参考:Vue v-slot 指令

HTML 参考:HTML <模板> 标签