You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 3中如何为插槽(slot)指定特定类型?

Vue 3 + TypeScript 为插槽指定类型

在Vue 3中,结合TypeScript给插槽指定类型可以通过以下两种方式实现:

1. 使用 defineSlots 宏(Vue 3.3+ 推荐方案)

Vue 3.3及以上版本提供了defineSlots宏,专门用于定义插槽的类型约束,直接在<script setup lang="ts">中使用即可。

示例1:约束默认插槽类型

如果要限制默认插槽只能接收文本或Vue节点类型的内容:

<template>
  <div>
    <slot />
  </div>
</template>

<script lang="ts" setup>
import { defineSlots } from 'vue'
import type { VNode } from 'vue'

// 定义默认插槽的类型:无传入props,返回内容为VNode/节点数组/字符串
defineSlots<{
  default: () => VNode | VNode[] | string
}>()
</script>

示例2:约束具名插槽及带props的插槽

如果是具名插槽,或者插槽需要接收父组件传递的props,也可以精准定义:

<template>
  <div>
    <slot name="header" :pageTitle="title" />
    <slot />
  </div>
</template>

<script lang="ts" setup>
import { defineSlots } from 'vue'
import type { VNode } from 'vue'

defineSlots<{
  // 默认插槽类型定义
  default: () => VNode | string
  // 具名插槽header:接收title属性,返回内容为VNode或字符串
  header: (props: { pageTitle: string }) => VNode | string
}>()

const title = 'Vue Slot Type Demo'
</script>

2. 手动类型推导(适配Vue 3.3以下版本)

如果你的Vue版本低于3.3,可以通过定义组件的插槽类型别名来间接约束:

<template>
  <div>
    <slot />
  </div>
</template>

<script lang="ts" setup>
import type { VNode, SlotContent } from 'vue'

// 定义默认插槽的类型
type DefaultSlot = SlotContent<{}>

// 定义组件的插槽类型约束
type MyComponentSlots = {
  default: DefaultSlot
}

// 后续可通过组件实例类型关联该约束
type MyComponent = {
  $slots: MyComponentSlots
}
</script>

补充说明

Vue中对应React ReactNode的插槽内容类型,通常可以用VNode、VNode[]、字符串、数字等,也可以直接使用Vue内置的SlotContent类型来做宽泛约束。

内容的提问来源于stack exchange,提问作者Asking

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:53:12