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

Vue3+TypeScript中如何用defineModel定义string[]|string类型的模型?

解决Vue 3.4中defineModel定义string[] | string联合类型的问题

你之前的写法错误在于,defineModel配置项里的type是用于运行时类型校验的,需要传入构造函数(比如String、Array),而不是TypeScript的类型语法(Array<string> | string这种写法只在TS编译时有效,运行时不识别)。

正确的写法分两种场景:

场景1:仅需要TypeScript类型约束(无需运行时校验)

直接通过defineModel的泛型参数指定联合类型即可:

<script setup lang="ts">
const model = defineModel<string[] | string>()
</script>

场景2:同时需要运行时类型校验 + TS类型约束

运行时校验的type字段传入包含对应构造函数的数组,再通过泛型指定具体的联合类型:

<script setup lang="ts">
const model = defineModel<string[] | string>({
  type: [String, Array]
})
</script>

如果需要设置默认值,可以在配置项中添加default:

<script setup lang="ts">
const model = defineModel<string[] | string>({
  type: [String, Array],
  default: () => [] // 或者默认字符串,比如 default: ''
})
</script>

至于Vuetify的v-select,它是通过multiple属性内部切换模型的类型逻辑——当multiple为true时,模型是数组类型;为false时是单个值类型,底层也是基于类似的联合类型定义来实现多类型支持的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:18:13