Vue <template> 元素

实例

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

  1. <ul>
  2. <li>Trolltunga</li>
  3. <template v-if="display">
  4. <li>Potato Point</li>
  5. <li>The souks of Marrakech</li>
  6. <li>Dry Tortugas</li>
  7. <li>Halong Bay</li>
  8. </template>
  9. <li>...</li>
  10. </ul>

定义与用法

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

当与 v-if, v-else-if, v-else, 或 v-for 一起使用时,内置的 <template> 元素会呈现 HTML 代码的一部分。

当与 v-slot 一起使用时,内置的 <template> 元素将 HTML 代码的一部分引导到指定的 slot。参见下面的实例1。

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

注意:当使用 SFC(*.vue)文件时,顶级 <template> 元素是一个结构要求。对于此类顶级 <template> 元素,不能使用 Vue 指令。

更多实例

实例 1

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

  1. <template>
  2. <h1>App.vue</h1>
  3. <p>The component has two div tags with one slot in each.</p>
  4. <slot-comp>
  5. <template v-slot:bottomSlot>
  6. <h4>To the bottom slot!</h4>
  7. <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>
  8. </template>
  9. <p>This goes into the default slot</p>
  10. </slot-comp>
  11. </template>
实例 2

使用 <template> 元素,可以使用 v-if 指令呈现多个元素。

  1. <div id="app">
  2. <template v-if="text.includes('pizza')">
  3. <p>The text includes the word 'pizza'</p>
  4. <img src="img_pizza.svg">
  5. </template>
  6. <p v-else>The word 'pizza' is not found in the text</p>
  7. </div>
  8. <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  9. <script>
  10. const app = Vue.createApp({
  11. data() {
  12. return {
  13. text: 'I like taco, pizza, Thai beef salad, pho soup and tagine.'
  14. }
  15. }
  16. })
  17. app.mount('#app')
  18. </script>

分类导航