我目前将 Nuxt 应用程序从版本 2 迁移到版本 3,同时还将 TypeScript 引入堆栈中。在我的一个组件模板中,我循环访问一组未知的对象键来创建单选或复选框输入列表。
<template
v-for="(optionValue, optionKey) in options"
:key="`filter-option-${optionKey}`"
>
<input
:id="optionKey.toString()"
v-model="selection"
class="filter-options-input visually-hidden"
:value="optionKey"
:name="name"
:type="type"
>
<label
:for="optionKey.toString()"
:class="['filter-options-label', `is-${type}`]"
>
{{ optionValue }}
</label>
</template>
代码创建了预期的必填字段,但我无法修复的是 <input>
上的以下 TypeScript 错误:value
属性:
An object literal cannot have multiple properties with the same name. ts(1117)
options
的类型定义看起来像这样:
type Option = {
[key: string]: string;
}
实际数据如下所示:
{
"portrait":"Hochformat",
"landscape":"Querformat",
"square":"Quadratisch"
}
或者像这样:
{
"akane-akane": "Akane, Akane",
"anita-staud": "Staud, Anita",
"anne-marie-chatelier": "Chatelier, Anne-Marie",
"anneli-schuetz": "Schütz, Anneli",
"annette-gundermann": "Gundermann, Annette",
"arno-mohr": "Mohr, Arno",
...
}
TypeScript 想在这里告诉我什么以及如何修复错误消息?
最佳答案
问题:
与 v-model
的错误输入有关作为 InputHTMLAttributes.value
的别名。根据docs , v-model
上
<input type="checkbox">
and<input type="radio">
usechecked
property ...
...与 value
无关属性。
我最初以为它来自 nuxt
(因为它是您链接的沙箱中唯一的依赖项,并且我在新的 vue
项目中没有看到相同的依赖项),所以我打开了 this ticket在他们的仓库中。
然而,事实证明,输入错误的罪魁祸首是 Volar,它是 Codesandbox 使用的 IDE 扩展(很可能也是您的 IDE 使用的)。
如果您想进一步研究这个问题,请随时在 Volar 的存储库上提出问题。
修复:
- 禁用 Volar
- 使用
v-bind
规避该问题语法:
<input
:id="optionKey.toString()"
v-model="selection"
class="filter-options-input visually-hidden"
v-bind="{ value: optionKey, name, type }"
/>
- 使用模板忽略来忽略它:
<input
...
v-model="selection"
...
:data-foo="/* ts-ignore */"
:value="optionKey"
...
/>
关于通过 Vue 3 (Nuxt 3) 中的对象键进行模板循环中输入值的 TypeScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75452800/