【问题标题】:Duplicate keys detected: '[object Object]'. This may cause an update error检测到重复键:“[object Object]”。这可能会导致更新错误
【发布时间】:2022-01-16 19:09:19
【问题描述】:
Before move After move

目前,我正在使用这种方法在数组中上下移动项目:

arrayMove(fromIndex, toIndex) {
  var element = this.blueprint.track[fromIndex];

  this.blueprint.track.splice(fromIndex, 1);
  this.blueprint.track.splice(toIndex, 0, element);
},

这是我要移动的物品:

<li
  v-for="(item, index) in blueprint.track"
  :key="item"
  ref="items"
  class="item card mb-24 position-relative"
>
  <Input
    class="item-title"
    v-model="item.title"
    label="Title"
    ref="title"
    :name="`item-title-${index + 1}`"
    @input="updateBlueprint"
  />
  <Textarea
    class="item-description"
    v-model="item.description"
    label="Description"
    ref="description"
    :name="`item-description-${index + 1}`"
    @input="updateBlueprint"
  />
</li>

这完全符合我的要求。但是,由于我将整个 item 用作 :key,因此每次移动项目时都会收到以下警告:

[Vue 警告]:避免使用非原始值作为键,而是使用字符串/数字值。 [Vue 警告]:检测到重复键:'[object Object]'。这可能会导致更新错误。

这是我的组件:

<script>
import { TextareaAutogrowDirective } from 'vue-textarea-autogrow-directive'

export default {
  directives: {
   'autogrow': TextareaAutogrowDirective
  },
  inheritAttrs: true,
  props: {
    name: {
      type: String,
      required: true,
    },
    label: {
      type: String,
      required: false,
    },
    value: {
      type: String,
    },
  },
  computed: {
    currentValue: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
};
</script>

<template>
  <div class="textarea">
    <label :for="name">{{ label }}</label>
    <textarea
      :name="name"
      v-model="currentValue"
      v-bind="$attrs"
      ref="input"
      v-autogrow
    />
  </div>
</template>

要查看autogrow 指令,您可以在此处找到:https://github.com/wrabit/vue-textarea-autogrow-directive/blob/master/src/VueTextareaAutogrowDirective.js

如何消除这些警告并使其按预期工作?我尝试过:key="item.key":key="index":key="item.title" 和类似的方法,但都没有奏效。有什么想法吗?

【问题讨论】:

  • 真的吗?整个问题是关于“自动增长”的,但不包括此功能的指令代码。以下只是观察。 Textarea 组件发出重复的input 事件-一次来自v-model,一次来自直接@input 侦听器。 inheritAttrs: true 毫无意义 - 这是默认设置。它的用法也很奇怪——为什么要有一个v-model 并同时监听@input 事件? :key="index" 与根本没有 key 相同
  • @MichalLevý 好吧,显然我不知道我在做什么,所以请记住这一点。你对我的问题有什么建设性的意见吗?
  • @MichalLevý 我清理了它,希望它更清晰。
  • 我尽量保持建设性。我告诉你添加autogrow指令的代码,而不是删除一堆(相当有用的)cmets......

标签: javascript vue.js vuejs2 vue-component nuxt.js


【解决方案1】:

根据这篇文章:https://deepsource.io/blog/key-attribute-vue-js/,我决定生成唯一 ID 并将它们分配给我的 items。一旦我这样做了,并使用了:key="item.id",一切都会按预期进行。

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 1970-01-01
    • 2020-02-27
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    相关资源
    最近更新 更多