[Vue warn]: Duplicate keys detected: x. This may cause an update error

后端 未结 6 521
我在风中等你
我在风中等你 2021-02-06 22:02

I keep getting an error when I add an item to the array which has duplicate id.

i.e.

active_widgets:Array[4]
0:Object
    id:1
    name:\"Text Blocks\"
         


        
6条回答
  •  一整个雨季
    2021-02-06 22:47

    You need to bind to the key with a unique value. Not doing so will cause problems in your application when a change in data for a component with one key updates that component and the other component with the duplicate key.

    You should assign a unique key property to each of the items in the active_widgets array and then bind the key to that property.


    Without seeing any of your code, I don't know what your unique use case is. But here are a couple ways you could add a unique key property to the items in your array.

    Here's an example doing that in the created method.

    created() {
      this.active_widgets.forEach((item, index) => this.$set(item, 'key', index));
    }
    

    If you need to add a unique key when an item is added to this array, you could maintain a counter and increment it each time an addition is made:

    let WidgetCount = 0;
    
    export default {
      data() {
        return { active_widgets: [] }
      },
      methods: {
        addWidget(id, name) {
          this.active_widgets.push({ 
            id, 
            name, 
            selected: false,
            set: false, 
            key: WidgetCount++
          })
        }
      }
    }
    

提交回复
热议问题