通过 Vue 3 (Nuxt 3) 中的对象键进行模板循环中输入值的 TypeScript 错误

标签 typescript vuejs3 nuxtjs3

我目前将 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)

这里提示: enter image description here

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 想在这里告诉我什么以及如何修复错误消息?

这是 Codesandbox 中的复制品:https://codesandbox.io/p/sandbox/agitated-mendeleev-ypytew?file=%2Fcomponents%2Finput-list.vue&selection=%5B%7B%22endColumn%22%3A14%2C%22endLineNumber%22%3A34%2C%22startColumn%22%3A14%2C%22startLineNumber%22%3A34%7D%5D

最佳答案

问题:
v-model 的错误输入有关作为 InputHTMLAttributes.value 的别名。根据docs , v-model

<input type="checkbox"> and <input type="radio"> use checked property ...

...与 value 无关属性。


我最初以为它来自 nuxt (因为它是您链接的沙箱中唯一的依赖项,并且我在新的 vue 项目中没有看到相同的依赖项),所以我打开了 this ticket在他们的仓库中。

然而,事实证明,输入错误的罪魁祸首是 Volar,它是 Codesandbox 使用的 IDE 扩展(很可能也是您的 IDE 使用的)。

如果您想进一步研究这个问题,请随时在 Volar 的存储库上提出问题。


修复:

  1. 禁用 Volar
  2. 使用 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/

    相关文章:

    angular - 两个订阅返回后 Typescript 执行函数

    vuejs3 - vue3 应用程序的 MSAL 重定向,vue 路由器哈希模式解析为 my_host/#/code=....rest-of-aad-response

    vue.js - 您正在运行Vue的esm-bundler构建。建议配置您的 bundler

    typescript - Nuxt3 : script setup cannot redeclare block-scoped variable

    Nuxt 3 中的 Axios 插件

    TypeScript - 在三元条件下执行多个操作

    typescript - 如何检查一种类型是否具有另一种类型的所有键但没有附加键?

    javascript - TypeScript 编译为 commonjs 和 umd

    typescript - 支持 Vue 3 的全日历

    environment-variables - 带有 Pinia 的 Nuxt 3 中的环境变量