【问题标题】:Expected v-bind directive on complex <template> / v-for复杂 <template> / v-for 上的预期 v-bind 指令
【发布时间】:2020-02-25 22:28:41
【问题描述】:

我在组件中尝试的复杂循环遇到了一个奇怪的问题。

<template v-for="(scorecard, scorecardIndex) in scorecards">
    <template v-for="(property, propertyIndex) in properties">
        <!-- Primary player -->
        <tr v-if="scorecardIndex === 0"
            v-bind:key="propertyIndex"> // THIS LINE
        </tr>
    </template>

    <!-- Secondary players, should only show score -->
    <tr v-if="scorecardIndex > 0"
        v-bind:key="scorecardIndex">    
    </tr>
</template>

我在哪里设置 v-bind:key="propertyIndex" 我在 VSCode 中收到以下错误

[vue/valid-v-for] 预期 'v-bind:key' 指令使用由 'v-for' 指令定义的变量。

奇怪的是,我的 vue 编译器实际上并没有出现错误,只是在 VSCode 中。这让我觉得它与 VSCode 直接有关,不一定与 Vue 本身有关。

【问题讨论】:

  • 这似乎是一个 eslint 插件问题。你会用吗?
  • 不应该 bind: 键与 v-for 在同一个标​​签中吗?

标签: vue.js visual-studio-code vue-component


【解决方案1】:

您从 eslint 收到此错误,该错误会检查您的代码是否存在可能的错误和错误的编码风格。

当您在&lt;template&gt; 上使用v-for 时,您需要确保在&lt;template&gt; 内的每个顶级元素上定义key。这是因为&lt;template&gt; 不是实际的 DOM 元素(在 Vue 模板中),因此其中的每个元素都将在 DOM 中的同一级别重复,这就是为什么在该 DOM 树级别的每个元素上都需要 key .

你有一个嵌套的&lt;template&gt;,每个都使用v-for,所以它变得有点复杂。您需要确保第一个 &lt;tr&gt; 的键使用 both v-fors 定义的变量。尽管在您的特定情况下,您使用 v-if 将创建的元素限制为仅第一行,因此 eslint 在这里过于迂腐。您可以像这样使警告静音:

<!-- eslint-disable-next-line vue/valid-v-for -->
<tr v-if="scorecardIndex === 0"
    v-bind:key="propertyIndex">
</tr>

但我认为你的顺序是错误的。首先检查它是否是第一行并然后重复一堆&lt;tr&gt;s 更有意义,而不是相反:

<template v-if="scorecardIndex === 0">
    <!-- Primary player -->
    <tr v-for="(property, propertyIndex) in properties"
        v-bind:key="propertyIndex">
    </tr>
</template>

最后,您会收到一些重复键警告,因为两组 &lt;tr&gt;s 都将使用键 0、1、2 等。也许给它们加前缀:

<template v-for="(scorecard, scorecardIndex) in scorecards">
    <template v-if="scorecardIndex === 0">
        <!-- Primary player -->
        <tr v-for="(property, propertyIndex) in properties"
            v-bind:key="'primary-' + propertyIndex">
        </tr>
    </template>

    <!-- Secondary players, should only show score -->
    <tr v-if="scorecardIndex > 0"
        v-bind:key="'secondary-' + scorecardIndex">    
    </tr>
</template>

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2021-04-23
    • 1970-01-01
    • 2020-06-14
    • 2019-05-31
    • 2023-03-19
    • 2018-09-30
    • 2021-03-26
    • 2020-04-18
    相关资源
    最近更新 更多