內建特殊元素
非元件
<component>, <slot> 和 <template> 是類似元件的功能和模板語法的一部分。它們不是真正的元件,在模板編譯過程中會被編譯掉。因此,它們通常在模板中以小寫形式書寫。
<component>
渲染動態元件或元素的“元元件”。
屬性
tsinterface 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>
表示模板中的槽內容出口。
屬性
tsinterface 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> 標籤作為佔位符。
詳情
只有在使用以下這些指令之一時,才會對
<template>進行特殊處理v-if、v-else-if或v-elsev-forv-slot
如果沒有這些指令中的任何一個,則將渲染為一個 原生的
<template>元素。具有
v-for的<template>也可以有一個key屬性。所有其他屬性和指令都將被丟棄,因為它們沒有對應元素就沒有意義。單檔案元件使用一個 頂級
<template>標籤 來包裝整個模板。這種用法與上述<template>的用法是分開的。頂級標籤不是模板本身的一部分,也不支援模板語法,如指令。另請參閱