Vuetify v-combobox 如何填充 API 返回的对象数组?
数据小许
结论
v-combobox 的 items 需要接收数组。题目中的 API 响应是一个对象,数组位于 barcodeTypeList 属性中。如果 api.getBarcodeTypes() 返回完整对象,直接将结果赋给 barcodeTypeList 会导致类型不匹配,需要先取出数组。
另外,示例模板中的属性写在了 <v-combobox> 开始标签外。Vue 组件的属性应写在开始标签内。
按 API 响应结构取出数组
如果 api.getBarcodeTypes() 返回题目展示的对象,可以为响应声明类型,再提取 barcodeTypeList:
interface BarcodeTypesResponse {
barcodeTypeList: BarcodeType[]
}
onMounted(async () => {
isLoading.value = true
try {
const response: BarcodeTypesResponse = await api.getBarcodeTypes()
barcodeTypeList.value = response.barcodeTypeList
} finally {
isLoading.value = false
}
})
如果 API 方法已经返回数组,直接赋值即可:
barcodeTypeList.value = await api.getBarcodeTypes()
题目没有提供 console.log 的具体输出,因此需要以实际返回值为准。检查 api.getBarcodeTypes() 的返回结构,确认它是数组,还是包含 barcodeTypeList 属性的对象。不要只凭变量名判断类型。
修正模板结构
属性应放在 <v-combobox> 开始标签中,例如:
<template>
<v-combobox
v-model="selectedBarcodeType"
label="Barcode type"
item-title="typeName"
item-value="typeIdentifier"
density="compact"
hide-details="auto"
:loading="isLoading"
:items="barcodeTypeList"
/>
</template>
Vue 模板会自动解包 ref,因此可以保留 :items="barcodeTypeList" 这种写法。
检查数据形状
如果仍然出现 Expected Array,可以在赋值前查看返回结果:
const response = await api.getBarcodeTypes()
console.log(response)
console.log(Array.isArray(response))
如果第一条日志显示响应对象中包含 barcodeTypeList 数组,就赋值 response.barcodeTypeList;如果响应本身是数组,则直接赋值。还要确认数组元素包含 typeName 和 typeIdentifier 字段,以匹配组件配置。
备注:内容仅供参考。
