跳轉到內容

內建特殊元素

非元件

<component>, <slot><template> 是類似元件的功能和模板語法的一部分。它們不是真正的元件,在模板編譯過程中會被編譯掉。因此,它們通常在模板中以小寫形式書寫。

<component>

渲染動態元件或元素的“元元件”。

  • 屬性

    ts
    interface DynamicComponentProps {
      is: string | Component
    }
  • 詳情

    實際要渲染的元件由 is 屬性確定。

    • is 是一個字串時,它可以是HTML標籤名或元件的註冊名。

    • 或者,is 也可以直接繫結到元件的定義。

  • 示例

    透過註冊名渲染元件(選項API)

    vue
    <script>
    import Foo from './Foo.vue'
    import Bar from './Bar.vue'
    
    export default {
      components: { Foo, Bar },
      data() {
        return {
          view: 'Foo'
        }
      }
    }
    </script>
    
    <template>
      <component :is="view" />
    </template>

    透過定義渲染元件(使用 <script setup> 的 Composition API)

    vue
    <script setup>
    import Foo from './Foo.vue'
    import Bar from './Bar.vue'
    </script>
    
    <template>
      <component :is="Math.random() > 0.5 ? Foo : Bar" />
    </template>

    渲染 HTML 元素

    模板
    <component :is="href ? 'a' : 'span'"></component>

    所有內建元件都可以傳遞給 is,但如果你想要按名稱傳遞,則必須註冊它們。例如

    vue
    <script>
    import { Transition, TransitionGroup } from 'vue'
    
    export default {
      components: {
        Transition,
        TransitionGroup
      }
    }
    </script>
    
    <template>
      <component :is="isGroup ? 'TransitionGroup' : 'Transition'">
        ...
      </component>
    </template>

    如果你直接將元件本身傳遞給 is 而不是其名稱,例如在 <script setup> 中,則不需要註冊。

    如果在 <component> 標籤上使用 v-model,模板編譯器將將其展開為 modelValue 屬性和 update:modelValue 事件監聽器,就像對任何其他元件所做的那樣。然而,這不會與原生 HTML 元素相容,例如 <input><select>。因此,使用 v-model 與動態建立的原生元素不會工作

    vue
    <script setup>
    import { ref } from 'vue'
    
    const tag = ref('input')
    const username = ref('')
    </script>
    
    <template>
      <!-- This won't work as 'input' is a native HTML element -->
      <component :is="tag" v-model="username" />
    </template>

    在實踐中,這種邊緣情況並不常見,因為原生表單欄位通常在真實應用中被封裝在元件中。如果你確實需要直接使用原生元素,則可以手動將 v-model 分解為一個屬性和事件。

  • 另請參閱 動態元件

<slot>

表示模板中的槽內容出口。

  • 屬性

    ts
    interface SlotProps {
      /**
       * Any props passed to <slot> to passed as arguments
       * for scoped slots
       */
      [key: string]: any
      /**
       * Reserved for specifying slot name.
       */
      name?: string
    }
  • 詳情

    可以使用 <slot> 元素的 name 屬性來指定槽名稱。如果沒有指定 name,則將渲染預設槽。傳遞給槽元素的額外屬性將作為作用域插槽的槽屬性傳遞給父元件中定義的插槽。

    元素本身將被其匹配的槽內容替換。

    Vue 模板中的 <slot> 元素被編譯成 JavaScript,因此不要與 原生的 <slot> 元素 混淆。

  • 另請參閱 元件 - 插槽

<template>

當想要使用內建指令而不在 DOM 中渲染元素時,使用 <template> 標籤作為佔位符。

內建特殊元素已載入