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

Nuxt 3正式版中自定义Vuetify文本框v-slot类型错误求助

修复Nuxt 3正式版中Vuetify自定义文本框的TypeScript类型错误

问题背景

之前使用Nuxt Beta版本搭配Vuetify开发的自定义文本框组件代码如下:

<script setup lang="ts">
</script>

<template>
   <v-text-field class="text-field" v-bind="$attrs" variant="solo">
     <template v-for="(_, name) in $slots" #[name]="slotData">
       <slot :name="name" v-bind="slotData" />
     </template>
   </v-text-field>
</template>

升级至Nuxt 3正式版后,出现以下TypeScript错误:

Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type 'Readonly<{ message?: ((arg: VMessageSlot) => VNode<RendererNode, RendererElement, { [key: string]: any; }>[]) | undefined; clear?: (() => VNode<...>[]) | undefined; ... 8 more ...; counter?: ((arg: VCounterSlot) => VNode<...>[]) | undefined; }>'.
   No index signature with a parameter of type 'string' was found on type 'Readonly<{ message?: ((arg: VMessageSlot) => VNode<RendererNode, RendererElement, { [key: string]: any; }>[]) | undefined; clear?: (() => VNode<...>[]) | undefined; ... 8 more ...; counter?: ((arg: VCounterSlot) => VNode<...>[]) | undefined; }>'.ts(7053)

错误出现在模板的#[name]位置。

解决方案

问题源于Nuxt 3正式版的TypeScript类型检查更严格,$slots的键类型被明确为固定的字符串集合,而v-for中name的默认类型是string | number,无法匹配插槽的具体类型。只需给name添加类型断言,明确它属于$slots的合法键即可:

<script setup lang="ts">
</script>

<template>
   <v-text-field class="text-field" v-bind="$attrs" variant="solo">
     <template v-for="(_, name) in $slots" #[name as keyof typeof $slots]="slotData">
       <slot :name="name" v-bind="slotData" />
     </template>
   </v-text-field>
</template>

说明

通过name as keyof typeof $slots的类型断言,告诉TypeScript当前的name是$slots对象的合法键,消除了隐式any的类型错误。这是因为Vuetify的组件插槽都有明确的类型定义,Nuxt 3正式版的类型系统会严格校验插槽名称的合法性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:27:30