0

When I try to run the following code, and I remove one item from the array, the item is not removed completely(there are other checkboxes part of each row which are not removed) I have added a :key="index" and doesn't help it. Nevertheless when I have changed the :key="index" to :key="item" it works, but then the problem is I get the warning [Vue warn]: Avoid using non-primitive value as key, use string/number value instead

<template>
  <div>
    <filters-list-item v-for="(item, index) in items" :key="index" v-on:deleteItem="deleteItem(index)" :items="items" :item="item"  :filterButtonSetting="filterButtonSetting" class="pb-3 pt-3 space-line"></m-filters-list-item>
    <div class="pt-3">
        <button class="btn" @click="add()">
            add
        </button>
    </div>
  </div>
</template>

<script>
import FiltersListItem from './FiltersListItem';

export default {
    name: 'FiltersList',
    components: {
        FiltersListItem
    },
    props: {
        items: Array,
        filterButtonSetting: Object
    },
    methods: {
        add() {
            this.items.push({});
        },
        deleteItem(index) {
            this.$delete(this.items, index);
        },

    }
};

4
  • 1
    You should definitely not use the index as the key in general but especially when moving or deleting items. If your backend hasn't provided IDs create them at the point of receiving the data. Commented Sep 10, 2019 at 10:59
  • That is very interesting... do you probably know of an example? thank you very much in advance Commented Sep 10, 2019 at 11:02
  • 1
    Perhaps a filter on the array? Something like: this.items = this.items.filter(i => i.id !== itemToDelete.id) Commented Sep 10, 2019 at 11:03
  • 1
    You can use something like uuid library, import uuid from 'uuid/v4' and items = data.map(item => ({ ...item, id: uuid() })) Commented Sep 10, 2019 at 11:32

1 Answer 1

2

Using the index is fine as long as you are not interacting with any of the elements in the loop.

But, if you are, then it is recommended not to do this.

You should use another unique item's identifier, maybe providing one from the backend.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.