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

Vue 3.4中defineModel非输入场景用法及TS错误解决

问题:使用defineModel传递数组时出现TypeScript类型错误

我尝试用Vue的defineModel替代繁琐的props/emit方式实现父子组件数组数据传递,代码能正常运行,但调用array.slice()时触发TypeScript错误:"Property 'slice' does not exist on type 'unknown'"。

父组件(App.vue)代码:

<script setup lang="ts">
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
  
const title = ref('v-model argument example with array')
const array = ref([1,2,3,4,5]);
</script>

<template>
  <h1>{{ title }}</h1>
  <MyComponent v-model:array="array" />
  <h2>Parent array: {{array}}</h2>
</template>

子组件(MyComponent.vue)原代码:

<script setup lang="ts">
const array  = defineModel('array')

function ShortenArray() {
  array.value = array.value.slice(1);
}
</script>

<template>
  <button @click="ShortenArray">Shorten Array</button>
  <p></p>
  child array: {{ array }}
</template>

解决方案:给defineModel指定明确类型

问题根源是defineModel在未指定类型时,TypeScript会将其推断为unknown类型,无法识别它是数组。只需显式声明类型即可解决:

方法1:使用泛型指定类型

<script setup lang="ts">
// 声明数组元素为number类型
const array = defineModel<number[]>('array')

function ShortenArray() {
  array.value = array.value.slice(1);
}
</script>

方法2:通过选项配置类型

<script setup lang="ts">
const array = defineModel('array', { 
  type: Array as () => number[] 
})

function ShortenArray() {
  array.value = array.value.slice(1);
}
</script>

显式指定类型后,TypeScript就能识别array.value是number数组,允许调用slice()等数组方法。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:23:28