特殊元素

发布时间 2024-01-07 13:27:27作者: yunChuans

<component>​

一个用于渲染动态组件或元素的“元组件”。

详细信息

  • 要渲染的实际组件由 is prop 决定。

  • 当 is 是字符串,它既可以是 HTML 标签名也可以是组件的注册名(或者是一个h函数?渲染组件,这在自定义组件中很实用,比如二次封装el-table)

  • 或者,is 也可以直接绑定到组件的定义。

按定义渲染组件 (<script setup> 组合式 API):

<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,比如 Transition, TransitionGroup

如果在 <component> 标签上使用 v-model,模板编译器会将其扩展为 modelValue prop 和 update:modelValue 事件监听器,就像对任何其他组件一样。但是,这与原生 HTML 元素不兼容,例如 <input> <select>。因此,在动态创建的原生元素上使用 v-model 将不起作用:

<script setup>
import { ref } from 'vue'

const tag = ref('input')
const username = ref('')
</script>

<template>
  <!-- 由于 'input' 是原生 HTML 元素,因此这个 v-model 不起作用 -->
  <component :is="tag" v-model="username" />
</template>

<template>​

当我们想要使用内置指令而不在 DOM 中渲染元素时,<template> 标签可以作为占位符使用。

详细信息

<template> 的特殊处理只有在它与以下任一指令一起使用时才会被触发:

  • v-if、v-else-if 或 v-else
  • v-for
  • v-slot
    如果这些指令都不存在,那么它将被渲染成一个原生的 <template> 元素。

带有 v-for 的 <template> 也可以有一个 key 属性。所有其他的属性和指令都将被丢弃,因为没有相应的元素,它们就没有意义。

单文件组件使用顶层的 <template> 标签来包裹整个模板。这种用法与上面描述的 <template> 使用方式是有区别的。该顶层标签不是模板本身的一部分,不支持指令等模板语法。