首页 > 解决方案 > 迭代中的元素期望有'v-bind:key'指令。eslint-plugin-vue?

问题描述

import Vue from 'vue';
export default {
    data() {
        return {
          cities : [
            'Bangalore','Chennai','Cochin','Delhi','Kolkata','Mumbai'
        ],

        value: '',
            open: false,
            current: 0
        }
    },
    props: {
        suggestions: {
            type: Array,
            required: true
        },
        selection: {
            type: String,
            required: true,
            twoWay: true
        }
    },
    computed: {
        matches() {
            return this.suggestions.filter((str) => {
                return str.indexOf(this.selection) >= 0;
            });
        },
        openSuggestion() {
            return this.selection !== "" &&
                   this.matches.length != 0 &&
                   this.open === true;
        }
    },
    methods: {
        enter() {
            this.selection = this.matches[this.current];
            this.open = false;
        },
        up() {
            if(this.current > 0)
                this.current--;
        },
        down() {
            if(this.current < this.matches.length - 1)
                this.current++;
        },
        isActive(index) {
            return index === this.current;
        },
        change() {
            if (this.open == false) {
                this.open = true;
                this.current = 0;
            }
        },
        suggestionClick(index) {
            this.selection = this.matches[index];
            this.open = false;
        },
    }
}
<template>
<div style="position:relative" v-bind:class="{'open':openSuggestion}">
    <input class="form-control" type="text" v-model="selection"
        @keydown.enter = 'enter'
        @keydown.down = 'down'
        @keydown.up = 'up'
        @input = 'change'
    />
    <ul class="dropdown-menu" style="width:100%">
        <li 
            v-for="suggestion in matches"
            v-bind:class="{'active': isActive($index)}"
            @click="suggestionClick($index)"
        >
            <a href="#">{{ suggestion }}</a>
        </li>
    </ul>
</div>
</template>

获取 eslint 错误 [vue/require-v-for-key] 迭代中的元素期望有 'v-bind:key' 指令。eslint-plugin-vue。

尝试更改为 v-bind:key="suggestion.id" 更改后,未显示 eslint 错误但问题是未显示自动完成(完全不起作用)。

如果代码中有任何错误,任何人都可以纠正我。

标签: javascriptvue.js

解决方案


在使用v-forVue 时,想知道如何识别列表中的项目。您不必这样做,但它被认为是最佳实践,因此 eslint 标记了它。

为了给出提示,您key向呈现的列表项添加一个具有唯一值(id、一些文本等)的属性,如下所示:

<li 
  v-for="suggestion in matches"
  v-bind:key="suggestion.id"
>

v-bind:key:key简而言之。该值必须是类型number | string | boolean | symbol

有关更多信息,请参阅文档:https ://vuejs.org/v2/guide/list.html#Maintaining-State


推荐阅读